Created
December 14, 2015 17:29
-
-
Save 9point6/04fb5186df69ebfc2d58 to your computer and use it in GitHub Desktop.
My solution to - http://play.elevatorsaga.com/
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) { | |
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