Created
February 3, 2018 07:48
-
-
Save spentacular/0a17f51a5479074eb87db8e1f926ff03 to your computer and use it in GitHub Desktop.
Stop light state machine
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
class StateMachine { | |
constructor(initialState, transitions) { | |
this.state = initialState | |
this.transitions = transitions | |
} | |
transition(next) { | |
const nextState = this.transitions[this.state][next] | |
if (!nextState) throw new Error(`invalid: ${this.state} -> ${next}`) | |
this.state = nextState | |
} | |
} | |
const machine = new StateMachine('green', { | |
green: { | |
TIMER: 'orange' | |
}, | |
orange: { | |
TIMER: 'red' | |
}, | |
red: { | |
TIMER: 'green' | |
} | |
}) | |
setInterval(() => { | |
machine.transition('TIMER') | |
console.log(machine.state) | |
}, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment