UNPKG

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