@thermopylae/lib.cache
Version:
107 lines (106 loc) • 2.62 kB
JavaScript
const PREV_SYM = Symbol.for('PREV_SYM_DLL');
const NEXT_SYM = Symbol.for('NEXT_SYM_DLL');
class DoublyLinkedListIterator {
node;
constructor(node) {
this.node = node;
}
next() {
if (this.node == null) {
return { value: null, done: true };
}
const result = { value: this.node, done: false };
this.node = this.node[NEXT_SYM];
return result;
}
}
class DoublyLinkedList {
head;
tail;
size;
constructor(startNode = null) {
if (startNode != null) {
startNode[NEXT_SYM] = null;
startNode[PREV_SYM] = null;
this.size = 1;
}
else {
this.size = 0;
}
this.head = startNode;
this.tail = startNode;
}
unshift(node) {
node[NEXT_SYM] = this.head;
node[PREV_SYM] = null;
if (this.head !== null) {
this.head[PREV_SYM] = node;
}
else {
this.tail = node;
}
this.head = node;
this.size += 1;
}
push(node) {
node[NEXT_SYM] = null;
node[PREV_SYM] = this.tail;
if (this.tail !== null) {
this.tail[NEXT_SYM] = node;
}
else {
this.head = node;
}
this.tail = node;
this.size += 1;
}
insertAfter(prevNode, newNode) {
newNode[NEXT_SYM] = prevNode[NEXT_SYM];
prevNode[NEXT_SYM] = newNode;
newNode[PREV_SYM] = prevNode;
if (newNode[NEXT_SYM] !== null) {
newNode[NEXT_SYM][PREV_SYM] = newNode;
}
else {
this.tail = newNode;
}
this.size += 1;
}
remove(node) {
if (node[PREV_SYM] !== null) {
node[PREV_SYM][NEXT_SYM] = node[NEXT_SYM];
}
else {
this.head = node[NEXT_SYM];
}
if (node[NEXT_SYM] !== null) {
node[NEXT_SYM][PREV_SYM] = node[PREV_SYM];
}
else {
this.tail = node[PREV_SYM];
}
node[PREV_SYM] = null;
node[NEXT_SYM] = null;
this.size -= 1;
}
toFront(node) {
this.remove(node);
this.unshift(node);
}
toTail(node) {
this.remove(node);
this.push(node);
}
[Symbol.iterator]() {
return new DoublyLinkedListIterator(this.head);
}
empty() {
return this.size === 0;
}
clear() {
this.head = null;
this.tail = null;
this.size = 0;
}
}
export { DoublyLinkedList, DoublyLinkedListIterator, NEXT_SYM, PREV_SYM };