간단한 유한 상태 머신 구현하기
function Automaton()
{
this.currentState = 'q1';
this.states = [{
'q1': 'q1',
'q2': 'q3',
'q3': 'q2'
},{
'q1': 'q2',
'q2': 'q2',
'q3': 'q2'
}];
}
Automaton.prototype.readCommands = function(commands)
{
commands.forEach(c=>
this.currentState = this.states[c][this.currentState]
);
return this.currentState=='q2';
}
var myAutomaton = new Automaton();
// Do anything necessaryto set up your automaton's states, q1, q2, and q3.
상태맵? 함수? 를 보다 간단하게 구현하고 리듀스를 사용하는게 더 좋을듯. 리듀스할때 꼭 타입이 같아야 할거 같아서 새로 함수를 만들어야 하나 했는데 그게 아닌가봄ㅋ
// this class-like stuff shouldn't be necessary here
function Automaton()
{
// this defines transition function
this.states = {
"q1": ["q1", "q2"],
"q2": ["q3", "q2"],
"q3": ["q2", "q2"]
};
}
Automaton.prototype.readCommands = function(commands)
{
// we don't even have to store current state anywhere
return "q2" === commands.reduce(function(state, input) {
return this.states[state][input];
}.bind(this), "q1");
}
var myAutomaton = new Automaton();