Skip to content

Instantly share code, notes, and snippets.

@oguzcanhuner
Last active November 15, 2019 15:57
Show Gist options
  • Save oguzcanhuner/6e333defaeed3453be49c0c40f418e5e to your computer and use it in GitHub Desktop.
Save oguzcanhuner/6e333defaeed3453be49c0c40f418e5e to your computer and use it in GitHub Desktop.
Elevator solution by Oz, Tim and Adam
{
init: function(elevators, floors) {
var self = this;
var awaitingFloors = {}
floors.forEach(function(floor){
floor.on("up_button_pressed", function() {
awaitingFloors[floor.floorNum()] = 1;
})
floor.on("down_button_pressed", function() {
awaitingFloors[floor.floorNum()] = 1;
})
})
elevators.forEach(function(elevator){
elevator.on("idle", function() {
targets = elevator.getPressedFloors()
nearestRequestedFloor = self.findNearestFloor(elevator.currentFloor(), targets)
nearestWaitingFloor = self.findNearestFloor(elevator.currentFloor(), Object.keys(awaitingFloors))
if(nearestRequestedFloor && elevator.loadFactor() >= 0.5){
floor = nearestRequestedFloor
}else{
floor = self.findNearestFloor(elevator.currentFloor(), [nearestRequestedFloor, nearestWaitingFloor])
}
if(floor){
elevator.goToFloor(floor);
delete awaitingFloors[floor]
}else{
elevator.goToFloor(0);
}
});
})
},
update: function(dt, elevators, floors) {
// We normally don't need to do anything here
},
findNearestFloor: function(currentFloor, floors) {
currentDistance = null
result = null
floors.forEach(function(floor){
if(!floor){
return
}
distance = Math.abs(currentFloor - floor)
if(!currentDistance || currentDistance > distance){
currentDistance = distance
result = floor
}
})
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment