UNPKG

typescript-algorithms-and-datastructures

Version:
93 lines 3.2 kB
(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports"], factory); } })(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class LinkedList { constructor() { this.head = LinkedList.emptyListItem(); this.length = 0; this.tail = LinkedList.emptyListItem(); this.tail.prev = this.head; this.head.next = this.tail; } static emptyListItem() { return ({ prev: null, value: null, next: null }); } static newItem(prev, next, value) { return ({ prev: prev, next: next, value: value }); } forEach(callback, thisArg = null) { var currentItem = this.head.next; var counter = 0; while (currentItem !== this.tail) { callback.call(thisArg, currentItem.value, counter, this); counter++; currentItem = currentItem.next; } } isEmpty() { return this.head.next === this.tail; } push(value) { this.addAfter(value, this.tail.prev); } pop() { var currentItem = this.tail.prev; if (this.isEmpty()) { throw new Error(`The linked list is empty.`); } this.removeItem(currentItem); return currentItem.value; } remove(value) { var currentItem = this.search(value); if (currentItem) { this.removeItem(currentItem); } else { throw new Error(`Cannot remove the value ${value}, it's not present in the linked list.`); } } shift() { var item = this.head.next; if (this.isEmpty()) { throw new Error(`The linked list is empty.`); } this.removeItem(item); return item.value; } unshift(value) { this.addAfter(value, this.head); } addAfter(value, itemAfter) { var newItem = LinkedList.newItem(itemAfter, itemAfter.next, value); itemAfter.next.prev = newItem; itemAfter.next = newItem; this.length++; } removeItem(item) { item.prev.next = item.next; item.next.prev = item.prev; this.length--; } search(value) { var currentItem = this.head.next; while (currentItem !== this.tail) { if (value === currentItem.value) { return currentItem; } currentItem = currentItem.next; } return null; } } exports.LinkedList = LinkedList; }); //# sourceMappingURL=LinkedList.js.map