forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapped_linkedlist.js
More file actions
136 lines (122 loc) · 2.61 KB
/
Copy pathmapped_linkedlist.js
File metadata and controls
136 lines (122 loc) · 2.61 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
'use strict';
const {
Map,
SymbolIterator,
} = primordials;
function push(root, value) {
const node = { value };
if (root.last) {
node.previous = root.last;
root.last.next = node;
} else {
root.first = node;
}
root.last = node;
root.length++;
return node;
}
function unshift(root, value) {
const node = { value };
if (root.first) {
node.next = root.first;
root.first.previous = node;
} else {
root.last = node;
}
root.first = node;
root.length++;
return node;
}
function pop(root) {
if (root.last) {
const { value } = root.last;
root.last = root.last.previous;
root.length--;
if (!root.last) {
root.first = root.last;
}
return value;
}
}
function getIterator(root, initialProperty, nextProperty) {
let node = root[initialProperty];
return {
next() {
if (!node) {
return { done: true };
}
const result = {
done: false,
value: node.value,
};
node = node[nextProperty];
return result;
},
[SymbolIterator]() {
return this;
}
};
}
function getMappedLinkedList(getKey = (value) => value) {
const map = new Map();
function addToMap(value, node, operation) {
const key = getKey(value);
let refs = map.get(key);
if (!refs) {
map.set(key, refs = { length: 0 });
}
operation(refs, node);
}
const root = { length: 0 };
return {
root,
get length() {
return root.length;
},
get first() {
return root.first?.value;
},
push(value) {
const node = push(root, value);
addToMap(value, node, push);
return this;
},
unshift(value) {
const node = unshift(root, value);
addToMap(value, node, unshift);
return this;
},
remove(value) {
const key = getKey(value);
const refs = map.get(key);
if (refs) {
const result = pop(refs);
if (result.previous) {
result.previous.next = result.next;
}
if (result === root.last) {
root.last = result.previous || result.next;
}
if (result.next) {
result.next.previous = result.previous;
}
if (result === root.first) {
root.first = result.next || result.previous;
}
if (refs.length === 0) {
map.delete(key);
}
root.length--;
return 1;
}
return 0;
},
[SymbolIterator]() {
return getIterator(root, 'first', 'next');
},
reverseIterator() {
return getIterator(root, 'last', 'previous');
},
};
}
module.exports = getMappedLinkedList;