Skip to content

Instantly share code, notes, and snippets.

@tomasr8
Last active October 16, 2016 17:53
Show Gist options
  • Save tomasr8/d302383948a59f484b577b4f8b12b1a2 to your computer and use it in GitHub Desktop.
Save tomasr8/d302383948a59f484b577b4f8b12b1a2 to your computer and use it in GitHub Desktop.
Simple finite state machine (FSM) implementation
"use strict";
function FSM(states, start, accepting) {
function _accepts(state, word) {
if (word === "") {
return accepting.indexOf(state) !== -1;
}
return _accepts(states[state][word[0]], word.slice(1));
}
return {
accepts(word) {
return _accepts(start, word);
}
};
}
// machine accepting binary strings (left to right) divisible by five
const states = {
"%0": {
"0": "%0",
"1": "%1"
},
"%1": {
"0": "%2",
"1": "%3"
},
"%2": {
"0": "%4",
"1": "%0"
},
"%3": {
"0": "%1",
"1": "%2"
},
"%4": {
"0": "%3",
"1": "%4"
}
};
const fsm = FSM(states, "%0", ["%0"]);
Array(11).fill(0).map((c, i) => {
return i.toString(2);
}).forEach(c => {
console.log(c, fsm.accepts(c));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment