-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist.js
55 lines (47 loc) · 1.19 KB
/
list.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
class List {
constructor () {
this._head = { next: null, previous: null, value: null }
this._head.next = this._head.previous = this._head
}
*[Symbol.iterator] () {
let iterator = this._head
while (iterator.next !== this._head) {
iterator = iterator.next
yield iterator.value
}
}
peek () {
return this._head.next.value
}
slice () {
const slice = []
for (const value of this) {
slice.push(value)
}
return slice
}
get empty () {
return this._head.next === this._head
}
push (value) {
const node = {
next: this._head,
previous: this._head.previous,
value: value
}
node.previous.next = node
node.next.previous = node
return node
}
// Point to self so that future calls to unlink are a no-op.
static unlink (node) {
node.next.previous = node.previous
node.previous.next = node.next
node.next = node.previous = node
return node.value
}
shift () {
return List.unlink(this._head.next)
}
}
module.exports = List