简单有限状态机的JavaScript实现(转)

[javascript] function FSM( config ) { if ( !( this instanceof arguments.callee ) ) { return new arguments.callee( config ); } this.initState = this.state = config.initState; this.f = config.f; this.endState = config.endState; this.endCallback = config.endCallback; } FSM.prototype = { test: function( event ) { var newState = this.f( this.state, event ); //测试新状态是否为终结状态。是则触发终结回调,反之将新状态设置为当前状态 if ( this.endState == newState ) { this.endCallback(); } else { this.state = newState; } } }; var locker = FSM({ initState: "", f: function( state, letter ) { var input = state + letter; return new RegExp( "^" + input ).test( this.endState ) ? input : this.initState; }, endState: "w3K~p0R%4", endCallback: function() { console.log( "Unlock Successfully!" ); } }); testPassword( locker, "abcdefw3K~p0Rfdsfw3" ); // 密码错误,无输出 testPassword( locker, "w3K~p0Rx4" ); // 密码错误,无输出 testPassword( locker, "w3K~p0R%4" ); // 密码正确,输出成功解锁信息 function testPassword( locker, pw ) { var a = pw.split( "" ); for( var i = 0; i < a.length; i++ ) { locker.test( a[i] ); } } [/javascript] 这个有限状态机感觉蛮好玩儿,就转了过来。 原始地址:http://casey-lai.appspot.com/blog/41
posted @ 2010-09-06 14:27  7hihi  阅读(152)  评论(0编辑  收藏  举报