Created
May 22, 2021 19:13
-
-
Save Ethan-Arrowood/b4ff316f4908cac5fd92a3cd1964ccbc to your computer and use it in GitHub Desktop.
A Stop Light state machine class built on Node.js EventEmitter
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
import { deepStrictEqual } from 'assert/strict'; | |
import { EventEmitter } from 'events'; | |
class StopLight extends EventEmitter { | |
static _data = new Map([ | |
[ 'GO', { color: 'green' } ], | |
[ 'STOP', { color: 'red' } ], | |
[ 'SLOW', { color: 'yellow' } ] | |
]) | |
constructor (timers) { | |
super() | |
this.timers = timers | |
this.on('go', function () { | |
this.state = 'GO' | |
this.log() | |
}) | |
this.on('slow', function () { | |
this.state = 'SLOW' | |
this.log() | |
}) | |
this.on('stop', function () { | |
this.state = 'STOP' | |
this.log() | |
}) | |
this.go() | |
} | |
get data () { | |
return StopLight._data.get(this.state) | |
} | |
go () { | |
this.emit('go') | |
setTimeout(() => this.slow(), this.timers.GO) | |
} | |
slow () { | |
this.emit('slow') | |
setTimeout(() => this.stop(), this.timers.SLOW) | |
} | |
stop () { | |
this.emit('stop') | |
setTimeout(() => this.go(), this.timers.STOP) | |
} | |
log () { | |
console.log(`State: ${this.state.padEnd(4)} | Data: ${JSON.stringify(this.data).padEnd(18)} | Timer: ${this.timers[this.state]}`) | |
} | |
} | |
const stopLight = new StopLight({ GO: 2000, SLOW: 1000, STOP: 3000 }) | |
stopLight.on('go', () => { | |
deepStrictEqual(stopLight.state, 'GO') | |
deepStrictEqual(stopLight.data, StopLight._data.get('GO')) | |
}) | |
stopLight.on('slow', () => { | |
deepStrictEqual(stopLight.state, 'SLOW') | |
deepStrictEqual(stopLight.data, StopLight._data.get('SLOW')) | |
}) | |
stopLight.on('stop', () => { | |
deepStrictEqual(stopLight.state, 'STOP') | |
deepStrictEqual(stopLight.data, StopLight._data.get('STOP')) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment