1 | /* eslint-disable */
|
2 | /*
|
3 |
|
4 | Queue.js
|
5 |
|
6 | A function to represent a queue
|
7 |
|
8 | Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
|
9 | the terms of the CC0 1.0 Universal legal code:
|
10 |
|
11 | http://creativecommons.org/publicdomain/zero/1.0/legalcode
|
12 |
|
13 | */
|
14 |
|
15 | /* Creates a new queue. A queue is a first-in-first-out (FIFO) data structure -
|
16 | * items are added to the end of the queue and removed from the front.
|
17 | */
|
18 | export default function Queue() {
|
19 | // initialise the queue and offset
|
20 | var queue = [];
|
21 | var offset = 0;
|
22 |
|
23 | // Returns the length of the queue.
|
24 | this.getLength = function() {
|
25 | return queue.length - offset;
|
26 | };
|
27 |
|
28 | // Returns true if the queue is empty, and false otherwise.
|
29 | this.isEmpty = function() {
|
30 | return queue.length == 0;
|
31 | };
|
32 |
|
33 | /* Enqueues the specified item. The parameter is:
|
34 | *
|
35 | * item - the item to enqueue
|
36 | */
|
37 | this.enqueue = function(item) {
|
38 | queue.push(item);
|
39 | };
|
40 |
|
41 | /* Dequeues an item and returns it. If the queue is empty, the value
|
42 | * 'undefined' is returned.
|
43 | */
|
44 | this.dequeue = function() {
|
45 | // if the queue is empty, return immediately
|
46 | if (queue.length == 0) return undefined;
|
47 |
|
48 | // store the item at the front of the queue
|
49 | var item = queue[offset];
|
50 |
|
51 | // increment the offset and remove the free space if necessary
|
52 | if (++offset * 2 >= queue.length) {
|
53 | queue = queue.slice(offset);
|
54 | offset = 0;
|
55 | }
|
56 |
|
57 | // return the dequeued item
|
58 | return item;
|
59 | };
|
60 |
|
61 | /* Returns the item at the front of the queue (without dequeuing it). If the
|
62 | * queue is empty then undefined is returned.
|
63 | */
|
64 | this.peek = function() {
|
65 | return queue.length > 0 ? queue[offset] : undefined;
|
66 | };
|
67 | }
|