-
Notifications
You must be signed in to change notification settings - Fork 0
/
MachineState.js
45 lines (40 loc) · 1.22 KB
/
MachineState.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import {
STATE_RUNNING,
DIR_LEFT
} from './consts'
import ViewState from './ViewState'
/**
* Represents a MachineState in given point in time.
*/
export default class MachineState {
constructor(states, finalStates, head, state, transitionFunction, tape) {
this.states = states
this.finalStates = finalStates
this.head = head
this.state = state
this.transitionFunction = transitionFunction
this.tape = tape
this.running = STATE_RUNNING
this.apply = this.apply.bind(this)
}
/**
* Applies machine step to the state.
*/
apply(machineStep) {
let added = false
if (this.head == -1) {
this.tape.unshift(machineStep.rewrite)
this.head = 0
added = true
} else if (this.head >= this.tape.length) {
this.tape.push(machineStep.rewrite)
added = true
} else {
this.tape[this.head] = machineStep.rewrite
}
let oldHead = this.head
this.head += (machineStep.direction === DIR_LEFT) ? -1 : +1;
this.state = machineStep.nextState
return new ViewState(machineStep.direction, oldHead, this.tape, this.state, added)
}
}