Skip to content

Instantly share code, notes, and snippets.

@zaypen
Created December 1, 2017 07:02
Show Gist options
  • Save zaypen/fc4238c07da649837f6a033131fa6c22 to your computer and use it in GitHub Desktop.
Save zaypen/fc4238c07da649837f6a033131fa6c22 to your computer and use it in GitHub Desktop.
{
init: (elevators, floors) => {
const max = array => Math.max.apply(null, array);
const min = array => Math.min.apply(null, array);
const asc = (a, b) => a - b;
const desc = (a, b) => b - a;
const upPressedFloors = [];
const downPressedFloors = [];
const sortElevatorQueue = elevator => {
elevator.destinationQueue.sort(elevator.destinationDirection === 'up' ? asc : desc);
elevator.checkDestinationQueue();
};
elevators.forEach(elevator => {
elevator.on('floor_button_pressed', (floorNum) => {
elevator.goToFloor(floorNum);
sortElevatorQueue(elevator);
});
elevator.on("passing_floor", (floorNum, direction) => {
if (elevator.loadFactor() >= 0.9) return;
if (upPressedFloors.find(f => f === floorNum) && direction === 'up') {
upPressedFloors.splice(upPressedFloors.indexOf(floorNum), 1);
elevator.goToFloor(floorNum, true);
}
if (downPressedFloors.find(f => f === floorNum) && direction === 'down') {
downPressedFloors.splice(downPressedFloors.indexOf(floorNum), 1);
elevator.goToFloor(floorNum, true);
}
});
elevator.on('stopped_at_floor', floorNum => {
// TODO indicate going up or down
});
elevator.on("idle", () => {
elevator.goToFloor(
[elevator.currentFloor(), min(upPressedFloors), max(downPressedFloors)]
.filter(f => f != -Infinity)
.sort((a, b) => Math.abs(b - elevator.currentFloor()) - Math.abs(a - elevator.currentFloor()))
.indexOf(0)
);
});
});
floors.forEach(floor => {
const floorNum = floor.floorNum();
floor.on('up_button_pressed', () => {
upPressedFloors.push(floorNum);
});
floor.on('down_button_pressed', () => {
downPressedFloors.push(floorNum);
});
});
},
update: (dt, elevators, floors) => {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment