added Queue.js library

This commit is contained in:
Richard Harrington 2013-08-17 17:04:10 -04:00
parent 044946ac93
commit 6ec94986bb
2 changed files with 85 additions and 0 deletions

View File

@ -4,6 +4,7 @@
<meta charset="UTF-8">
<title>Robotwar</title>
<script type="text/javascript" src="js/lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript" src="js/lib/Queue.js"></script>
</head>
<body>
<p>

84
public/js/lib/Queue.js Normal file
View File

@ -0,0 +1,84 @@
/*
Queue.js
A function to represent a queue
Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
the terms of the CC0 1.0 Universal legal code:
http://creativecommons.org/publicdomain/zero/1.0/legalcode
*/
/* Creates a new queue. A queue is a first-in-first-out (FIFO) data structure -
* items are added to the end of the queue and removed from the front.
*/
function Queue(){
// initialise the queue and offset
var queue = [];
var offset = 0;
/* Returns the length of the queue.
*/
this.getLength = function(){
// return the length of the queue
return (queue.length - offset);
}
/* Returns true if the queue is empty, and false otherwise.
*/
this.isEmpty = function(){
// return whether the queue is empty
return (queue.length == 0);
}
/* Enqueues the specified item. The parameter is:
*
* item - the item to enqueue
*/
this.enqueue = function(item){
// enqueue the item
queue.push(item);
}
/* Dequeues an item and returns it. If the queue is empty then undefined is
* returned.
*/
this.dequeue = function(){
// if the queue is empty, return undefined
if (queue.length == 0) return undefined;
// store the item at the front of the queue
var item = queue[offset];
// increment the offset and remove the free space if necessary
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
// return the dequeued item
return item;
}
/* Returns the item at the front of the queue (without dequeuing it). If the
* queue is empty then undefined is returned.
*/
this.peek = function(){
// return the item at the front of the queue
return (queue.length > 0 ? queue[offset] : undefined);
}
}