Skip to content

Instantly share code, notes, and snippets.

@josh-stevens
Last active October 19, 2018 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josh-stevens/3375614428602f089c75dd9f998aa841 to your computer and use it in GitHub Desktop.
Save josh-stevens/3375614428602f089c75dd9f998aa841 to your computer and use it in GitHub Desktop.
Solution for elevator challenge 8
{
init: function(elevators, floors) {
elevators.forEach(elevator => {
elevator.on('floor_button_pressed', (num) => {
elevator.goToFloor(num);
});
});
floorHandler = (floor) => {
let closest, idle;
let distance = Infinity;
elevators.forEach(e => {
// check each elevator for the closest one
let thisDistance = Math.abs(e.currentFloor() - floor.floorNum());
if (thisDistance < distance) {
closest = e;
distance = thisDistance;
}
// but also check for idle elevators
if (!e.destinationQueue.length) {
idle = e;
}
})
idle ? idle.goToFloor(floor.floorNum()) : closest.goToFloor(floor.floorNum(), true)
}
floors.forEach(floor => {
floor.on('up_button_pressed', floorHandler.bind(this, floor))
floor.on('down_button_pressed', floorHandler.bind(this, floor))
})
},
update: function(dt, elevators, floors) {
// We normally don't need to do anything here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment