This repository was archived by the owner on Oct 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathqueue.js
More file actions
78 lines (65 loc) · 1.44 KB
/
queue.js
File metadata and controls
78 lines (65 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* Data Structures with JavaScript :: Queue
*
* A linear data structure.
*
* FIFO (First In First Out)
*
* Operations of a Queue:
* - enqueue: which adds an element to the collection
* - dequeue: which removes the first added element that was not yet removed
*
* https://en.wikipedia.org/wiki/Queue_(abstract_data_type)
*/
function Queue() {
this.items = []; // Container for storing data
this.maxsize = 1024; // Maximum number of elements
}
/**
* Add an element to the collection
*/
Queue.prototype.enqueue = function(item) {
if (this.items.length >= this.maxsize) {
// overflow error
return undefined;
}
this.items.push(item);
}
/**
* Remove an element from the collection
*/
Queue.prototype.dequeue = function() {
if (this.items.length <= 0) {
// underflow error
return undefined;
}
return this.items.shift();
}
/**
* Observes the first element without removing it from the queue
*/
Queue.prototype.peek = function() {
if (this.items.length == 0) {
// is empty
return undefined;
}
return this.items[0]
}
/**
* Returns the number of elements in the queue
*/
Queue.prototype.size = function() {
return this.items.length;
}
/**
* Example
*/
var queue = new Queue();
queue.enqueue('a');
console.log(queue.peek());
queue.enqueue('b');
console.log(queue.peek());
console.log(queue.dequeue());
console.log(queue.peek());
console.log(queue.size());
console.log(queue.peek());