Skip to content

Instantly share code, notes, and snippets.

@spentacular
Created February 3, 2018 07:48
Show Gist options
  • Save spentacular/0a17f51a5479074eb87db8e1f926ff03 to your computer and use it in GitHub Desktop.
Save spentacular/0a17f51a5479074eb87db8e1f926ff03 to your computer and use it in GitHub Desktop.
Stop light state machine
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