Last active
October 16, 2016 17:53
-
-
Save tomasr8/d302383948a59f484b577b4f8b12b1a2 to your computer and use it in GitHub Desktop.
Simple finite state machine (FSM) implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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