finito

Finite state machine that emits events and is compatible to EventEmitter.

npm install finito
3 downloads in the last week
12 downloads in the last month

Finito

Finito is a finite automata implementation that emits events and is compatible to the EventEmitter interface.

Installation

npm install finito

Usage

Transitions

addTransition

The addTransition method takes a single transition and adds it to the automata.

addTransition from, via, to
Finito = require 'finito'
fin = new Finito

fin.addTransition 'state1', 'foo', 'state2'

Constructor

The Finito class optionally takes transitions as argument. For example

Finito = require 'finito'

fin = new Finito
    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 into state1.

Reading

read

The read method reads a single character, that means it executes a single transition.

readWord

The readWord method reads a word, splits it up in characters and feeds it to the automata. It takes a string or an array.

Events

change

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 = new Finito
    state1:
        'foo': 'state2'
    state2:
        'bar': 'state1'

fin.setStart 'state1'

fin.on 'change', (from, via, to) ->
    console.log "Changed state from #{from} to #{to} by reading '#{via}'"

fin.read 'foo'
fin.read 'bar'
Changed state from state1 to state2 by reading 'foo'
Changed state from state2 to state1 by reading 'bar'

finish

The finish event is emitted, when the automata reaches a final state. Final states are added by calling addFinal 'state'.

Finito = require 'finito'
fin = new Finito
    default:
        'foo': 'bar'

fin.addFinal 'bar'

fin.on 'finish', ->
    console.log 'FINISHED!'

fin.read 'bar'
fin.read 'foo'

Example

A simple example for a finite automata is detection of parity.

Graph

Graph of parity automata

With Finito

Finito = require 'finito'

fin = new Finito
    even:
        '0': 'even'
        '1': 'odd'
    odd:
        '0': 'odd'
        '1': 'even'

fin.on 'change', (from, via, to) ->
    console.log from+'\t--['+via+']-->\t'+to

fin.state.current = 'even'
fin.readWord '1101'
even    --[1]-->    odd
odd     --[1]-->    even
even    --[0]-->    even
even    --[1]-->    odd
npm loves you