UNPKG

1.57 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2010-2016 original author or authors */
2/** @author Brian Cavalier */
3/** @author John Hann */
4
5/**
6 * Doubly linked list
7 * @constructor
8 */
9export default function LinkedList () {
10 this.head = null
11 this.length = 0
12}
13
14/**
15 * Add a node to the end of the list
16 * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to add
17 */
18LinkedList.prototype.add = function (x) {
19 if (this.head !== null) {
20 this.head.prev = x
21 x.next = this.head
22 }
23 this.head = x
24 ++this.length
25}
26
27/**
28 * Remove the provided node from the list
29 * @param {{prev:Object|null, next:Object|null, dispose:function}} x node to remove
30 */
31LinkedList.prototype.remove = function (x) { // eslint-disable-line complexity
32 --this.length
33 if (x === this.head) {
34 this.head = this.head.next
35 }
36 if (x.next !== null) {
37 x.next.prev = x.prev
38 x.next = null
39 }
40 if (x.prev !== null) {
41 x.prev.next = x.next
42 x.prev = null
43 }
44}
45
46/**
47 * @returns {boolean} true iff there are no nodes in the list
48 */
49LinkedList.prototype.isEmpty = function () {
50 return this.length === 0
51}
52
53/**
54 * Dispose all nodes
55 * @returns {Promise} promise that fulfills when all nodes have been disposed,
56 * or rejects if an error occurs while disposing
57 */
58LinkedList.prototype.dispose = function () {
59 if (this.isEmpty()) {
60 return Promise.resolve()
61 }
62
63 var promises = []
64 var x = this.head
65 this.head = null
66 this.length = 0
67
68 while (x !== null) {
69 promises.push(x.dispose())
70 x = x.next
71 }
72
73 return Promise.all(promises)
74}