Finite state machine that emits events and is compatible to EventEmitter.
Finito is a finite automata implementation that emits events and is compatible to the EventEmitter interface.
npm install finito
addTransition method takes a single transition and adds it to the
Finito = require 'finito'fin =finaddTransition 'state1''foo''state2'
Finito class optionally takes transitions as argument.
Finito = require 'finito'fin =state1:foo: 'state2'state2:bar: 'state1'
means that if the automata is in
state1 and reads
foo it will go into
state2 and if the automata is in
state2 and reads
bar it will go
read method reads a single character, that means it executes a single
readWord method reads a word, splits it up in characters and feeds it to
the automata. It takes a string or an array.
The change event is emitted, when the automata changes its state. The event handler gets the previous state, the character that was read and the new state.
Finito = require 'finito'fin =state1:'foo': 'state2'state2:'bar': 'state1'finsetStart 'state1'finon 'change'consolelog "Changed state from to by reading ''"finread 'foo'finread 'bar'
Changed state from state1 to state2 by reading 'foo'Changed state from state2 to state1 by reading 'bar'
The finish event is emitted, when the automata reaches a final state. Final
states are added by calling
Finito = require 'finito'fin =default:'foo': 'bar'finaddFinal 'bar'finon 'finish'->consolelog 'FINISHED!'finread 'bar'finread 'foo'
A simple example for a finite automata is detection of parity.
Finito = require 'finito'fin =even:'0': 'even''1': 'odd'odd:'0': 'odd''1': 'even'finon 'change'consolelog from+'\t--['+via+']-->\t'+tofin.state.current = 'even'finreadWord '1101'
even ----> oddodd ----> eveneven ----> eveneven ----> odd