|
| 1 | +import Node from './Node.js'; |
| 2 | +import Iterator from './Iterator.js'; |
| 3 | +import ReverseIterator from './ReverseIterator.js'; |
| 4 | + |
1 | 5 | /** |
2 | 6 | * Doubly linked list implementation |
3 | 7 | * making use of dummy nodes for the |
4 | 8 | * sake of simplicity. |
5 | 9 | */ |
6 | | - |
7 | | -export function DoublyLinkedList() { |
| 10 | +export default function DoublyLinkedList() { |
8 | 11 | this.front = new Node(null, null, null); |
9 | 12 | this.back = new Node(this.front, null, null); |
10 | 13 | this.front.next = this.back; |
11 | 14 | this.length = 0; |
12 | 15 | } |
13 | 16 |
|
14 | | -export function Node(prev, next, value) { |
15 | | - this.prev = prev; |
16 | | - this.next = next; |
17 | | - this.value = value; |
18 | | -} |
19 | | - |
20 | | -export function Iterator(front, back, current) { |
21 | | - this.front = front; |
22 | | - this.back = back; |
23 | | - this.current = current; |
24 | | -} |
25 | | - |
26 | | -export function ReverseIterator(front, back, current) { |
27 | | - this.front = front; |
28 | | - this.back = back; |
29 | | - this.current = current; |
30 | | -} |
31 | | - |
32 | 17 | DoublyLinkedList.prototype.insertAfter = function (iterator, value) { |
33 | 18 | const prev = iterator.current; |
34 | 19 |
|
@@ -170,31 +155,14 @@ DoublyLinkedList.prototype.rend = function () { |
170 | 155 | return this.riterator(this.front); |
171 | 156 | }; |
172 | 157 |
|
173 | | -Iterator.prototype.copy = function () { |
174 | | - return new Iterator(this.front, this.back, this.current); |
175 | | -}; |
176 | | - |
177 | | -ReverseIterator.prototype.copy = function () { |
178 | | - return new ReverseIterator(this.front, this.back, this.current); |
179 | | -}; |
180 | | - |
181 | | -// eslint-disable-next-line no-multi-assign |
182 | | -Iterator.prototype.next = ReverseIterator.prototype.prev = function () { |
183 | | - // eslint-disable-next-line no-multi-assign |
184 | | - const c = (this.current = this.current.next); |
185 | | - |
186 | | - return c === this.back ? {done: true} : {value: c.value, done: false}; |
187 | | -}; |
188 | | - |
189 | | -// eslint-disable-next-line no-multi-assign |
190 | | -Iterator.prototype.prev = ReverseIterator.prototype.next = function () { |
191 | | - // eslint-disable-next-line no-multi-assign |
192 | | - const c = (this.current = this.current.prev); |
193 | | - |
194 | | - return c === this.front ? {done: true} : {value: c.value, done: false}; |
| 158 | +const from = (iterable) => { |
| 159 | + const list = new DoublyLinkedList(); |
| 160 | + for (const value of iterable) list.push(value); |
| 161 | + return list; |
195 | 162 | }; |
196 | 163 |
|
197 | 164 | DoublyLinkedList.prototype[Symbol.iterator] = DoublyLinkedList.prototype.begin; |
198 | 165 | DoublyLinkedList.Node = Node; |
199 | 166 | DoublyLinkedList.Iterator = Iterator; |
200 | 167 | DoublyLinkedList.ReverseIterator = ReverseIterator; |
| 168 | +DoublyLinkedList.from = from; |
0 commit comments