forked from Wizcorp/list-Fifo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·93 lines (82 loc) · 1.89 KB
/
index.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
90
91
92
93
/**
* FIFO LIST Class
*
* @author Brice Chevalier
*
* @desc First in last out data structure
*
* Method Time Complexity
* ___________________________________
*
* add O(1)
* pop O(1)
* getFirst O(1)
* getLast O(1)
* getCount O(1)
* apply O(n)
* clear O(n)
*
* Memory Complexity in O(n)
*/
function Node(obj, previous) {
this.object = obj;
this.previous = previous;
this.next = null;
}
function FifoList() {
this.count = 0;
this.last = null;
this.first = null;
}
FifoList.prototype.add = function (obj) {
this.count += 1;
var newNode = new Node(obj, this.last);
if (this.last === null) {
this.last = newNode;
this.first = newNode;
} else {
// insertion after the this.last one
this.last.next = newNode;
this.last = newNode;
}
return newNode;
};
FifoList.prototype.pop = function () {
if (this.first !== null) {
var node = this.first;
var result = this.first.object;
this.first = this.first.next;
if (this.first !== null) {
this.first.previous = null;
} else {
this.last = null;
}
node.next = null;
this.count -= 1;
return result;
}
};
FifoList.prototype.getLast = function () {
return this.last;
};
FifoList.prototype.getFirst = function () {
return this.first;
};
FifoList.prototype.clear = function () {
this.last = null;
this.first = null;
};
FifoList.prototype.getCount = function () {
return this.count;
};
FifoList.prototype.forEach = function (processingFunc, params) {
for (var current = this.first; current; current = current.next) {
processingFunc(current.object, params);
}
};
FifoList.prototype.forEachReverse = function (processingFunc, params) {
for (var current = this.last; current; current = current.previous) {
processingFunc(current.object, params);
}
};
module.exports = FifoList;