-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.js
89 lines (78 loc) · 1.78 KB
/
queue.js
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
79
80
81
82
83
84
85
86
87
88
89
const LinkedList = require('../linked-lists/linked-list');
/* Usage Example:
// tag::snippet[]
const queue = new Queue();
queue.enqueue('a');
queue.enqueue('b');
queue.dequeue(); //↪️ a
queue.enqueue('c');
queue.dequeue(); //↪️ b
queue.dequeue(); //↪️ c
// end::snippet[]
// */
// tag::constructor[]
/**
* Data structure where we add and remove elements in a first-in, first-out (FIFO) fashion
*/
class Queue {
constructor(iterable = []) {
this.items = new LinkedList(iterable);
}
// end::constructor[]
// tag::enqueue[]
/**
* Add element to the back of the queue.
* Runtime: O(1)
* @param {any} item
* @returns {queue} instance to allow chaining.
*/
enqueue(item) {
this.items.addLast(item);
return this;
}
// end::enqueue[]
// tag::dequeue[]
/**
* Remove element from the front of the queue.
* Runtime: O(1)
* @returns {any} removed value.
*/
dequeue() {
return this.items.removeFirst();
}
// end::dequeue[]
/**
* Size of the queue
*/
get size() {
return this.items.size;
}
/**
* Return true if is empty false otherwise true
*/
isEmpty() {
return !this.items.size;
}
/**
* Return the most recent value or null if empty.
*/
back() {
if (this.isEmpty()) return null;
return this.items.last.value;
}
/**
* Return oldest value from the queue or null if empty.
* (Peek at the next value to be dequeue)
*/
front() {
if (this.isEmpty()) return null;
return this.items.first.value;
}
}
// Aliases
Queue.prototype.peek = Queue.prototype.front;
Queue.prototype.add = Queue.prototype.enqueue;
Queue.prototype.push = Queue.prototype.enqueue;
Queue.prototype.remove = Queue.prototype.dequeue;
Queue.prototype.pop = Queue.prototype.dequeue;
module.exports = Queue;