Skip to content

Instantly share code, notes, and snippets.

@radleta
Created January 23, 2015 13:07
Show Gist options
  • Save radleta/1c7f3042a24610588725 to your computer and use it in GitHub Desktop.
Save radleta/1c7f3042a24610588725 to your computer and use it in GitHub Desktop.
Elevator Saga Challenge #4
// URL: http://play.elevatorsaga.com/#challenge=4
{
init: function(elevators, floors) {
function initElevator(elevator) {
elevator.on("idle", function() {});
elevator.on("floor_button_pressed", function(floorNum) {
elevator.goToFloor(floorNum, true);
});
elevator.on("passing_floor", function(floorNum, direction) {
var stopAtFloor = false;
elevator.destinationQueue = elevator.destinationQueue.filter(function (n, i) {
if (n == floorNum) {
stopAtFloor = true;
}
return n != floorNum;
});
if (stopAtFloor) {
elevator.checkDestinationQueue();
elevator.goToFloor(floorNum, true);
}
});
};
function findNearestElevator(floor) {
var possibilities = elevators
.map(function (e) {
return {
elevator: e,
distance: e.destinationQueue.length == 0 ? -1 : Math.abs(floor.floorNum() - e.currentFloor()),
};
});
possibilities.sort(function (left, right) {
return left.distance - right.distance;
});
return possibilities[0].elevator;
};
function initFloor(floor) {
floor.on("up_button_pressed", function() {
// Maybe tell an elevator to go to this floor?
findNearestElevator(floor).goToFloor(floor.floorNum());
});
floor.on("down_button_pressed", function() {
// Maybe tell an elevator to go to this floor?
findNearestElevator(floor).goToFloor(floor.floorNum());
});
};
elevators.forEach(initElevator);
floors.forEach(initFloor);
},
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