Skip to content

Instantly share code, notes, and snippets.

@9point6
Created December 14, 2015 17:29
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 9point6/04fb5186df69ebfc2d58 to your computer and use it in GitHub Desktop.
Save 9point6/04fb5186df69ebfc2d58 to your computer and use it in GitHub Desktop.
{
init: function(elevators, floors) {
function getLeastBusyElevator(elevators) {
return elevators.reduce(function (currentLeast, thisElevator) {
if (thisElevator.destinationQueue.length < currentLeast.destinationQueue.length &&
thisElevator.loadFactor() < 0.75
) {
return thisElevator;
} else {
return currentLeast;
}
}, elevators[Math.floor(elevators.length * Math.random())]);
}
function elevatorAlreadyGoingToFloor(elevators, floorNum) {
return elevators.some(function(elevator) {
return elevator.inDestinationQueue(floorNum);
});
}
elevators.forEach(function (elevator) {
elevator.inDestinationQueue = function(floorNum) {
return elevator.destinationQueue.indexOf(floorNum) !== -1;
}
elevator.removeFromDestinationQueue = function(floorNum) {
elevator.destinationQueue = elevator.destinationQueue.filter(function(item) {
return item !== floorNum;
});
elevator.checkDestinationQueue();
}
elevator.on("idle", function() {
elevator.goingUpIndicator(true);
elevator.goingDownIndicator(true);
});
elevator.on("floor_button_pressed", function(floorNum) {
if (!elevator.inDestinationQueue(floorNum)) {
elevator.goToFloor(floorNum);
}
});
elevator.on("passing_floor", function(floorNum, direction) {
if (elevator.inDestinationQueue(floorNum)) {
elevator.removeFromDestinationQueue(floorNum);
elevator.goToFloor(floorNum, true);
}
});
elevator.on("stopped_at_floor", function(floorNum) {
if (elevator.loadFactor() > 0.5) {
switch (elevator.destinationDirection()) {
case "up":
elevator.goingUpIndicator(true);
elevator.goingDownIndicator(false);
break;
case "down":
elevator.goingUpIndicator(false);
elevator.goingDownIndicator(true);
break;
}
} else {
elevator.goingUpIndicator(true);
elevator.goingDownIndicator(true);
}
});
});
floors.forEach(function (floor) {
floor.on("up_button_pressed down_button_pressed", function() {
if (!elevatorAlreadyGoingToFloor(elevators, floor.floorNum())) {
getLeastBusyElevator(elevators).goToFloor(floor.floorNum());
}
});
});
},
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