Newer
Older
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
var fifo = function () {
/**
* an unbounded fifo queue.
*/
const Queue = function () {
this.data = [];
this.push = function (e) {
this.data.push(e);
};
/**
* note: pop() will return undefined when there is not enough element.
*/
this.pop = function () {
return this.data.shift();
};
};
/**
* a bounded fifo queue.
*/
const BoundedQueue = function (capacity) {
this.capacity = capacity;
this.data = [];
/**
* push new element to the BoundedQueue. if there is no room for it,
* remove the oldest element from the queue.
*/
this.push = function (e) {
console.assert(this.data.length <= this.capacity, "bounded queue data size is invalid");
if (this.data.length === this.capacity) {
this.data.shift();
}
this.data.push(e);
};
/**
* note: pop() will return undefined when there is not enough element.
*/
this.pop = function () {
return this.data.shift();
};
};
const testFIFO = function () {
var q = new Queue();
q.push(1);
q.push(2);
q.push(3);
console.assert(q.pop() === 1);
console.assert(q.pop() === 2);
console.assert(q.pop() === 3);
q = new BoundedQueue(3);
q.push(1);
q.push(2);
q.push(3);
console.assert(q.pop() === 1);
console.assert(q.pop() === 2);
console.assert(q.pop() === 3);
q = new BoundedQueue(3);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
console.assert(q.pop() === 2);
console.assert(q.pop() === 3);
console.assert(q.pop() === 4);
};
// run all tests
testFIFO();
return {
Queue: Queue,
BoundedQueue: BoundedQueue,
};
}();