-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (54 loc) · 1.58 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
function getName(node) {
return node.name
}
function headNode(first, collection) {
return collection[first]
}
function next(node, collection) {
return collection[node.next]
}
function nodeAt(index, first, collection) {
let node = headNode(first, collection)
for (let i = 0; i < index; i++) {
node = next(node, collection)
}
return node
}
function addressAt(index, first, collection) {
if (index === 0) {
return first
} else {
let node = nodeAt(index - 1, first, collection)
return node.next
}
}
function indexAt(node, collection, first) {
let head = headNode(first, collection)
let currentNode = head
let index = 0
while (currentNode !== node) {
currentNode = next(currentNode, collection)
index++
}
return index
}
function insertNodeAt(index, address, first, collection) {
let newNode = collection[address]
let previousNode = nodeAt(index - 1, first, collection)
let nextNode = nodeAt(index, first, collection)
let nextIndex = indexAt(nextNode, collection, first)
let nextAddress = addressAt(nextIndex, first, collection)
previousNode.next = address
newNode.next = nextAddress
return collection
}
function deleteNodeAt(index, first, collection) {
let deletableAddress = addressAt(index, first, collection)
let previousNode = nodeAt(index - 1, first, collection)
let nextNode = nodeAt(index + 1, first, collection)
let nextIndex = indexAt(nextNode, collection, first)
let nextAddress = addressAt(nextIndex, first, collection)
previousNode.next = nextAddress
collection[deletableAddress] = null
return collection
}