-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinite-state-machine.js
More file actions
52 lines (46 loc) · 1.37 KB
/
Copy pathfinite-state-machine.js
File metadata and controls
52 lines (46 loc) · 1.37 KB
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
46
47
48
49
50
51
52
class FSM {
/**
*
* @param {String[]} alphabet
* @param {String[]} states
* @param {String} currentState
* @param {String[]} finiteStates
* @param {Object} transitions
*/
constructor(alphabet, states, currentState, finiteStates, transitions) {
this.alphabet = alphabet;
this.states = states;
this.initialState = currentState;
this.currentState = currentState;
this.finiteStates = finiteStates;
this.transitions = transitions;
}
// Проверяем на наличие символа в переходе
_checkExistTransition(state, symbol) {
return (this.transitions[state] && this.transitions[state][symbol])
}
_changeState(symbol) {
if (this._checkExistTransition(this.currentState, symbol)) {
this.currentState = this.transitions[this.currentState][symbol]
} else {
throw new Error(`No transitions from ${this.currentState} by ${symbol}`)
}
}
_checkBelongAlphabet(symbol) {
if (this.alphabet.includes(symbol)) {
return true
} else {
throw new Error(`Unknown symbol ${symbol}`)
}
}
test(value) {
this.currentState = this.initialState;
for (let symbol of value) {
this._checkBelongAlphabet(symbol);
this._changeState(symbol)
// console.log(this.currentState)
}
return this.finiteStates.includes(this.currentState)
}
}
module.exports = FSM;