Last active
October 19, 2018 14:46
-
-
Save josh-stevens/3375614428602f089c75dd9f998aa841 to your computer and use it in GitHub Desktop.
Solution for elevator challenge 8
This file contains hidden or 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
{ | |
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