Skip to content

Instantly share code, notes, and snippets.

@Buggytheclown
Created June 23, 2019 17:01
Show Gist options
  • Save Buggytheclown/8b9f9b4ee62eed2a3f9df45c10d392f6 to your computer and use it in GitHub Desktop.
Save Buggytheclown/8b9f9b4ee62eed2a3f9df45c10d392f6 to your computer and use it in GitHub Desktop.
Simple Automaton (Finite State Machine)
const q3 = () => q2;
const q2 = command => (command === '0' ? q3 : q2);
const q1 = command => (command === '1' ? q2 : q1);
function Automaton1() {
return {
readCommands(commands) {
const lastState = commands.reduce(
(state, command) => state(command),
q1
);
return lastState.name === q2.name;
},
};
}
function* Q3() {
const command = yield 'q3';
yield* Q2();
}
function* Q2() {
const command = yield 'q2';
yield* command === '0' ? Q3() : Q2();
}
function* Q1() {
const command = yield 'q1';
yield* command === '1' ? Q2() : Q1();
}
function Automaton2() {
return {
readCommands(commands) {
const q = Q1();
q.next();
const lastQ = commands.reduce(
(_, command) => q.next(command),
null
);
return lastQ.value === 'q2';
},
};
}
var myAutomaton = new Automaton2();
console.assert(myAutomaton.readCommands(['1']), true);
console.assert(myAutomaton.readCommands(['1', '0', '0', '1']), true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment