Skip to content

Instantly share code, notes, and snippets.

@GeDiez
Created July 31, 2019 22:11
Show Gist options
  • Save GeDiez/dcc72f3693fd77bea4182fb163d16e52 to your computer and use it in GitHub Desktop.
Save GeDiez/dcc72f3693fd77bea4182fb163d16e52 to your computer and use it in GitHub Desktop.
simulate lift using js
const initialState = {
floor: 0,
isOpen: false,
direction: 'up',
}
function Lift (state = initialState) {
console.table(state)
function request (floor) {
return Lift({
...state,
direction,
floor
})
}
function setFloor(floor) {
return Lift({
...state,
floor
})
}
function open () {
return Lift({
...state,
isOpen: true
})
}
function close () {
return Lift({
...state,
isOpen: false
})
}
return {
open,
close,
request
}
}
function LiftQueue (lift) {
return function (liftTarget, callback) {
if (lift.floor !== liftTarget.floor) {
setTimeout(() => {
console.log("DING!")
liftTarget.open().close()
callback(LiftQueue(liftTarget))
}, Math.abs(lift.floor - liftTarget.floor) * 1000)
}
}
}
@GeDiez
Copy link
Author

GeDiez commented Jul 31, 2019

running:
copy this script to some REPL like in the browser

  Lift()
    .setFloor(4), 
  function(callToLiftAgain) { 
    // you can call the lift once at time the lift has arrived 
    callToLiftAgain( Lift().setFloor(1) )
  }
)```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment