Skip to content

Instantly share code, notes, and snippets.

@dmoss18
Last active August 30, 2022 18:25
Show Gist options
  • Save dmoss18/dedbff1a97a92dbd6eb8009e1f049cfc to your computer and use it in GitHub Desktop.
Save dmoss18/dedbff1a97a92dbd6eb8009e1f049cfc to your computer and use it in GitHub Desktop.
The baby periodically gets hungry or sleepy. The babysitter needs to be notified whenever the baby's state changes so he/she can help the baby. Add functionality to notify the babysitter. Please also support replacing a babysitter.
const States = {
Default: 0,
Hungry: 1,
Sleepy: 2
}
class Baby {
currentState = States.Default
feedInterval = 0
sleepInterval = 0
start() {
this.feedInterval = setInterval(
() => this.updateState(States.Hungry), 2000)
this.sleepInterval = setInterval(
() => this.updateState(States.Sleepy), 5000)
}
stop() {
clearInterval(this.feedInterval)
clearInterval(this.sleepInterval)
}
updateState(state) {
this.currentState = state
console.log("The baby's state is ", state)
}
feed() {
if (this.currentState != States.Hungry) {
throw 'Not hungry'
}
this.currentState = States.Default
}
putToSleep() {
if (this.currentState != States.Sleepy) {
throw 'Not sleepy'
}
this.currentState = States.Default
}
}
class Babysitter {
}
const baby = new Baby()
const babySitter = new Babysitter()
baby.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment