admin管理员组文章数量:1420181
This picture depicts finite state machine parsing "nice" string.
The question is how would it look like in JS code?
EDIT
Picture from link above:
This picture depicts finite state machine parsing "nice" string.
The question is how would it look like in JS code?
EDIT
Picture from link above:
Share Improve this question edited Nov 17, 2011 at 19:02 Anne 27.1k9 gold badges67 silver badges71 bronze badges asked Nov 17, 2011 at 18:56 DrStrangeLoveDrStrangeLove 11.6k16 gold badges63 silver badges73 bronze badges 02 Answers
Reset to default 4According to wikipedia(where your link points) this refers to an "Acceptor FSM" and "By definition, the languages accepted by FSMs are the regular languages". One could say that it will be just /^nice$/.test(somestring)
. If this helps and you need more info on regular expressions take a look at RegExp.
I did a little FSM work in Javascript on a project just recently. My code, adapted for the case above, looks like this - you have a factory to make the state automaton, which is just a sequence of steps it's trying to match:
function fsmAutomatonFactory(tests) {
var step = 0;
var state = false; // acceptance state
return {
testNext: function(element) {
// matches current step
if (tests[step].test(element)) {
// advance step
step++;
return true;
}
// no match
return false;
},
getState: function() {
// all steps pleted successfully
return step >= tests.length
}
}
}
Now you can set up an automaton with a series of tests, and run the input series through it:
function fsmTest(str) {
// set up automaton
var tests = [
{ test: function(l) { return l == 'n' }},
{ test: function(l) { return l == 'i' }},
{ test: function(l) { return l == 'c' }},
{ test: function(l) { return l == 'e' }}
];
var automaton = fsmAutomatonFactory(tests);
// run the test letter by letter
for (var x=0; x<str.length; x++) {
// you could break early here if you wanted
automaton.testNext(str[x]);
}
return automaton.getState();
}
This is a lot of code for str == "nice"
, but it scales relatively well to more plex inputs and tests. This works for a linear pattern like your case; if you needed branching or more plex logic, you might need to implement a state transition table or other mechanism to handle transitions other than state++
.
本文标签: javascriptFinite State Machine parsingStack Overflow
版权声明:本文标题:javascript - Finite State Machine parsing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745322375a2653434.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论