Skip to content

Instantly share code, notes, and snippets.

@Xiphe
Created April 3, 2015 12:24
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 Xiphe/33edf417d5f92c551f2f to your computer and use it in GitHub Desktop.
Save Xiphe/33edf417d5f92c551f2f to your computer and use it in GitHub Desktop.
Elevator Saga
{
init: function(elevators, floors) {
function unique(arr) {
var a = arr.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
var upDown = ['up', 'down'];
var floorsWithPeople = {
up: [],
down: []
}
floors.forEach(function(floor) {
upDown.forEach(function(direction) {
floor.on(direction + '_button_pressed', function() {
var floorNum = floor.floorNum();
if (!peopleOnFloor(floorNum, direction)) {
floorsWithPeople[direction].push(floorNum);
}
});
});
});
function waitForNextFloor(elevator) {
var nextFloor = unique(floorsWithPeople.up.concat(floorsWithPeople.down))[0];
if (nextFloor !== undefined) {
goToFloor(elevator, nextFloor);
} else {
window.setTimeout(function() {
waitForNextFloor(elevator);
}, 100);
}
}
function getDirection(from, to) {
return from > to ? 'down' : 'up';
}
function peopleOnFloor(floorNum, direction) {
return floorsWithPeople[direction].indexOf(floorNum) >= 0;
}
function goToFloor(elevator, floorNum, force) {
var direction = getDirection(elevator.currentFloor(), floorNum);
var i = floorsWithPeople[direction].indexOf(floorNum);
if (i >= 0) {
floorsWithPeople[direction].splice(i, 1);
}
cleanupQueue(elevator);
elevator.goToFloor(floorNum, force);
cleanupQueue(elevator);
}
function cleanupQueue(elevator) {
elevator.destinationQueue.forEach(function(floorNum, i) {
var people = false;
upDown.forEach(function(dir) {
if (floorsWithPeople[dir].indexOf(floorNum) >= 0) {
people = true;
}
});
if (!people && elevator.getPressedFloors().indexOf(floorNum) == -1) {
elevator.destinationQueue.splice(i, 1);
}
});
elevator.checkDestinationQueue();
};
elevators.forEach(function(elevator) {
elevator.on("idle", function() {
waitForNextFloor(elevator);
});
elevator.on('floor_button_pressed', function(floorNum) {
goToFloor(elevator, floorNum);
});
elevator.on('passing_floor', function(floorNum, direction) {
if (peopleOnFloor(floorNum, direction)) {
goToFloor(elevator, floorNum, true);
}
});
});
},
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