-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (45 loc) · 1.09 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
'use strict'
const next = Symbol('Next node')
const prev = Symbol('Previous node')
module.exports = {
next: next,
prev: prev,
create: create,
insertBefore: insertBefore,
insertAfter: insertAfter,
before: before,
after: after,
toArray: toArray,
}
function create(items){
if (!items) throw new Error('Expected an array')
const first = items[0]
if (!first) throw new Error('At least one item is required')
first[prev] = null
first[next] = null
for (let i = 1;i < items.length;i++) insertAfter(first, items[i])
}
function insertBefore(base, item){
const tail = base[prev]
if (tail !== null) tail[next] = item
base[prev] = item
item[prev] = tail
item[next] = base
}
function insertAfter(base, item){
const head = base[next]
if (head !== null) head[prev] = item
base[next] = item
item[prev] = base
item[next] = head
}
function before(item){ return item[prev] }
function after(item){ return item[next] }
function toArray(begin){
const arr = [begin]
let next = begin
while (next = after(next)) arr.push(next)
next = begin
while (next = before(next)) arr.unshift(next)
return arr
}