x3-linkedlist
Version:
A doubly linked list implementation
73 lines • 2.44 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Represents an Item within LinkedList.
* An item holds a value and the links to other LinkedListItem's
* LinkedListItem's can only be attached behind.
* Theirfor, to add one before, before has to add one behind.
*/
class LinkedListItem {
/**
* @param value Value to be held
* @param unlinkCleanup Function to run on unlink() call. Usually used by LinkedList to fix first and last pointers and reduce length.
*/
constructor(value,
/**
*
*/
unlinkCleanup) {
this.value = value;
this.unlinkCleanup = unlinkCleanup;
}
/**
* This will link given LinkListItem behind this item.
* If there's already a LinkedListItem linked behind, it will be relinked accordingly
* @param item LinkListItem to be inserted behind this one
*/
insertBehind(item) {
item.insertBefore(this);
if (this.behind) {
let itemChainEnd = item;
while (itemChainEnd.behind)
itemChainEnd = itemChainEnd.behind;
this.behind.insertBefore(itemChainEnd);
itemChainEnd.insertBehind(this.behind);
}
this.behind = item;
}
/**
* Unlinks this LinkedListItem and calls unlinkCleanup
* @param unchain If true, additionally removes the reference to the item before and behind
* @see LinkedListItem#unlinkCleanup
*/
unlink(unchain = false) {
if (this.before)
this.before.behind = this.behind;
if (this.behind) {
this.behind.before = this.before;
}
if (this.unlinkCleanup) {
this.unlinkCleanup(this);
}
this.unlinkCleanup = undefined;
if (unchain) {
this.before = this.behind = undefined;
}
}
/**
* Item given will be inserted before this item.
* unlinkCleanup will be copied if neccessary.
* This function is protected, because LinkedListItem's can only be attached behind.
*
* @param before
* @see insertBehind
*/
insertBefore(before) {
this.before = before;
if (!this.unlinkCleanup) {
this.unlinkCleanup = before.unlinkCleanup;
}
}
}
exports.LinkedListItem = LinkedListItem;
//# sourceMappingURL=LinkedListItem.js.map