UNPKG

@thermopylae/lib.cache

Version:
99 lines (98 loc) 2.42 kB
const NEXT_SYM = Symbol('NEXT_SYM_SLL'); class SingleLinkedListIterator { 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 SingleLinkedList { head; tail; size; constructor(startNode = null) { if (startNode != null) { startNode[NEXT_SYM] = null; this.size = 1; } else { this.size = 0; } this.head = startNode; this.tail = startNode; } unshift(node) { node[NEXT_SYM] = this.head; this.head = node; if (this.tail == null) { this.tail = node; } this.size += 1; } push(node) { node[NEXT_SYM] = null; if (this.tail == null) { this.head = node; } else { this.tail[NEXT_SYM] = node; } this.tail = node; this.size += 1; } insertAfter(prevNode, newNode) { newNode[NEXT_SYM] = prevNode[NEXT_SYM]; prevNode[NEXT_SYM] = newNode; if (newNode[NEXT_SYM] == null) { this.tail = newNode; } this.size += 1; } remove(node) { if (this.head === node) { this.head = node[NEXT_SYM]; if (this.head == null) { this.tail = null; } } else { let current = this.head[NEXT_SYM]; let previous = this.head; while (current !== node) { previous = current; current = current[NEXT_SYM]; } previous[NEXT_SYM] = current[NEXT_SYM]; if (this.tail === node) { this.tail = previous; } } node[NEXT_SYM] = null; this.size -= 1; } toFront(node) { if (this.head === node) { return; } this.remove(node); this.unshift(node); } [Symbol.iterator]() { return new SingleLinkedListIterator(this.head); } empty() { return this.size === 0; } clear() { this.head = null; this.size = 0; } } export { SingleLinkedList, SingleLinkedListIterator, NEXT_SYM };