All files / src/internal/engines linked-list-engine.ts

100% Statements 132/132
97.36% Branches 37/38
100% Functions 49/49
100% Lines 126/126

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371                                    106x   106x                                         739329x 739329x 739329x 739329x 739329x           21535x 13737x 13737x 8802x 8802x   13737x                           8802x         3292x 3292x       2978x 2978x 2978x 17x 17x       3189x 3189x       3140x 3140x       15113x               301x                       70753x 70753x 70753x       1549614x       1486090x 1486090x 1486090x 1486090x       1272x 1272x                     7500x 7500x 7500x         7500x 7500x       3042x       26900x       1991x       21653x       53001x       4141x       7119x       70753x                     204351x 204351x       2189x 2189x       165361x 165361x       104532x 104532x       11059x       104758x       4999x       251808x       13422x 13422x 13422x       107078x 107078x 107078x       4112x 4112x 4112x 217294x 217294x 110144x 110144x   217294x   4112x       847x 847x 303150x 303150x 303150x 303150x 303150x   847x 847x 847x 847x       25379x             54528x         16225x       6063x       3056x       1537x       4507x       1534x 1534x       4431x 4431x       5924x 5924x 5924x         124739x 124739x 124739x         11889x 11889x 8877x       3012x                 739329x 739329x 619765x 739329x 108912x 739329x 739329x 739329x         234883x 234883x 234883x 210050x 234883x 123269x 234883x 234883x 234883x      
// The engine behind `LinkedList`: a doubly linked list of internal nodes with plain fields. A
// node is handed out only through a `NodeHandle`, made the first time the node is returned and then
// reused. The public class holds one engine and delegates to it, so nothing here reaches the
// published types except through the `LinkedListNode` interface.
 
import { IllegalArgumentError, IllegalStateError } from '../../errors/errors'
import type { LinkedListNode } from '../../interfaces/linked-list-node'
import type { Deque } from '../../interfaces/queue'
import { describeValue } from '../checks'
import { defineProperty } from '../intrinsics'
import { INSPECT } from '../output'
import { AbstractDeque, type DequeWalker } from '../skeletons/abstract-deque'
import { ReversedDeque } from '../views/reversed-deque'
 
// Module-local key for a handle's internal node. It is not a registered symbol, so no other code
// can name it, and the property is non-enumerable, so `Object.keys`, `JSON.stringify`, `for…in`
// and spread never show it. Reflection (`Object.getOwnPropertySymbols`) still sees it; the state
// is hidden, not protected.
const NODE: unique symbol = Symbol('node')
 
const REMOVED = 'LinkedListNode.value: the node has been removed from its list'
 
/**
 * An element's place in a `LinkedListEngine`. Never handed out: `handleOf` wraps it. A removed
 * node keeps its value and its handle but no reference to its list or to other nodes.
 *
 * @internal
 */
class ListNode<E> {
  item: E
  next: ListNode<E> | undefined
  prev: ListNode<E> | undefined
  list: LinkedListEngine<E> | undefined
  handle: NodeHandle<E> | undefined
 
  constructor(
    item: E,
    prev: ListNode<E> | undefined,
    next: ListNode<E> | undefined,
    list: LinkedListEngine<E>,
  ) {
    this.item = item
    this.next = next
    this.prev = prev
    this.list = list
    this.handle = undefined
  }
}
 
/** Returns the handle of `node`, made on first use and then the same object; `undefined` for none. */
function handleOf<E>(node: ListNode<E> | undefined): NodeHandle<E> | undefined {
  if (node === undefined) return undefined
  let handle = node.handle
  if (handle === undefined) {
    handle = new NodeHandle(node)
    node.handle = handle
  }
  return handle
}
 
/**
 * The public face of a node of a `LinkedListEngine`, handed out as a `LinkedListNode`. Its only
 * own property is the internal node, non-enumerable. A handle of a removed node keeps its value
 * but answers `undefined` for its neighbours.
 *
 * @internal
 */
export class NodeHandle<E> implements LinkedListNode<E> {
  declare readonly [NODE]: ListNode<E>
 
  constructor(node: ListNode<E>) {
    defineProperty(this, NODE, { value: node })
  }
 
  get value(): E {
    // An object made from this prototype has no node: it reads `undefined` without throwing.
    const node = this[NODE] as ListNode<E> | undefined
    return node === undefined ? (undefined as E) : node.item
  }
 
  set value(value: E) {
    const node = this[NODE] as ListNode<E> | undefined
    const list = node === undefined ? undefined : node.list
    if (list === undefined) throw new IllegalStateError(REMOVED)
    ;(node as ListNode<E>).item = value
    list.changeCounter.replaced()
  }
 
  get next(): NodeHandle<E> | undefined {
    const node = this[NODE] as ListNode<E> | undefined
    return node === undefined ? undefined : handleOf(node.next)
  }
 
  get previous(): NodeHandle<E> | undefined {
    const node = this[NODE] as ListNode<E> | undefined
    return node === undefined ? undefined : handleOf(node.prev)
  }
 
  get [Symbol.toStringTag](): string {
    return 'LinkedListNode'
  }
 
  [INSPECT](
    _depth: number | null,
    options: object,
    inspect: (value: unknown, options: object) => string,
  ): string {
    return `LinkedListNode { value: ${inspect(this.value, options)} }`
  }
}
 
/** Walks the nodes of a `LinkedListEngine`, holding the node it returns next. */
class NodeWalker<E> implements DequeWalker<E> {
  private upcoming: ListNode<E> | undefined
  private last: ListNode<E> | undefined
  private readonly list: LinkedListEngine<E>
  private readonly fromBack: boolean
 
  constructor(list: LinkedListEngine<E>, fromBack: boolean) {
    this.list = list
    this.fromBack = fromBack
    this.upcoming = fromBack ? list.tailNode : list.headNode
  }
 
  hasNext(): boolean {
    return this.upcoming !== undefined
  }
 
  next(): E {
    const node = this.upcoming as ListNode<E>
    this.last = node
    this.upcoming = this.fromBack ? node.prev : node.next
    return node.item
  }
 
  remove(): void {
    this.list.unlink(this.last as ListNode<E>)
    this.last = undefined
  }
}
 
/**
 * A deque stored as a doubly linked list of nodes. A node leaving the list is cut loose: by
 * `detach` for a single node, and node by node in `clearAll`. No walk recurses.
 *
 * @internal
 */
export class LinkedListEngine<E> extends AbstractDeque<E> {
  private head: ListNode<E> | undefined = undefined
  private tail: ListNode<E> | undefined = undefined
  private length = 0
  private readonly facade: Deque<E>
 
  /** @param facade - The public list, for identity and callbacks. */
  constructor(facade: Deque<E>) {
    super()
    this.facade = facade
  }
 
  override get owner(): Deque<E> {
    return this.facade
  }
 
  override get storesEmpty(): boolean {
    return true
  }
 
  protected override get noun(): string {
    return 'list'
  }
 
  get [Symbol.toStringTag](): string {
    return 'LinkedList'
  }
 
  get size(): number {
    return this.length
  }
 
  peekFront(): E {
    return (this.head as ListNode<E>).item
  }
 
  peekBack(): E {
    return (this.tail as ListNode<E>).item
  }
 
  walker(fromBack: boolean): DequeWalker<E> {
    return new NodeWalker(this, fromBack)
  }
 
  ensureRoom(_count: number, _where: string): void {
    // No limit but memory.
  }
 
  // The adders and removers at the ends, defined here rather than inherited, so each call site
  // sees one class. Every element is allowed, so there is nothing to check.
 
  override add(element: E): this {
    this.link(this.tail, undefined, element)
    return this
  }
 
  override addLast(element: E): this {
    this.link(this.tail, undefined, element)
    return this
  }
 
  override push(element: E): this {
    this.link(this.tail, undefined, element)
    return this
  }
 
  override addFirst(element: E): this {
    this.link(undefined, this.head, element)
    return this
  }
 
  override poll(): E | undefined {
    return this.length === 0 ? undefined : this.takeFront()
  }
 
  override pop(): E | undefined {
    return this.length === 0 ? undefined : this.takeBack()
  }
 
  insertFront(element: E): void {
    this.link(undefined, this.head, element)
  }
 
  insertBack(element: E): void {
    this.link(this.tail, undefined, element)
  }
 
  takeFront(): E {
    const node = this.head as ListNode<E>
    this.unlink(node)
    return node.item
  }
 
  takeBack(): E {
    const node = this.tail as ListNode<E>
    this.unlink(node)
    return node.item
  }
 
  compact(flags: readonly boolean[]): void {
    let node = this.head
    let index = 0
    while (node !== undefined) {
      const next = node.next
      if (flags[index++] === true) {
        this.detach(node)
        this.length--
      }
      node = next
    }
    this.changes.structural()
  }
 
  clearAll(): void {
    let node = this.head
    while (node !== undefined) {
      const next = node.next
      node.next = undefined
      node.prev = undefined
      node.list = undefined
      node = next
    }
    this.head = undefined
    this.tail = undefined
    this.length = 0
    this.changes.structural()
  }
 
  reversed(): Deque<E> {
    return new ReversedDeque(this)
  }
 
  // ── Handles ──
 
  /** The first internal node, for walkers. */
  get headNode(): ListNode<E> | undefined {
    return this.head
  }
 
  /** The last internal node, for walkers. */
  get tailNode(): ListNode<E> | undefined {
    return this.tail
  }
 
  firstNode(): NodeHandle<E> | undefined {
    return handleOf(this.head)
  }
 
  lastNode(): NodeHandle<E> | undefined {
    return handleOf(this.tail)
  }
 
  addFirstNode(element: E): NodeHandle<E> {
    return handleOf(this.link(undefined, this.head, element)) as NodeHandle<E>
  }
 
  addLastNode(element: E): NodeHandle<E> {
    return handleOf(this.link(this.tail, undefined, element)) as NodeHandle<E>
  }
 
  insertBefore(node: unknown, element: E): NodeHandle<E> {
    const at = this.requireNode(node, 'LinkedList.insertBefore')
    return handleOf(this.link(at.prev, at, element)) as NodeHandle<E>
  }
 
  insertAfter(node: unknown, element: E): NodeHandle<E> {
    const at = this.requireNode(node, 'LinkedList.insertAfter')
    return handleOf(this.link(at, at.next, element)) as NodeHandle<E>
  }
 
  removeNode(node: unknown): E {
    const at = this.requireNode(node, 'LinkedList.removeNode')
    this.unlink(at)
    return at.item
  }
 
  /** Removes `node`, a node of this list, as one structural change. */
  unlink(node: ListNode<E>): void {
    this.detach(node)
    this.length--
    this.changes.structural()
  }
 
  /** Returns the internal node of `node` when it is a handle of this list; otherwise throws, before any change. */
  private requireNode(node: unknown, where: string): ListNode<E> {
    const at = node instanceof NodeHandle ? (node[NODE] as ListNode<E> | undefined) : undefined
    if (at === undefined || at.list !== this) {
      throw new IllegalArgumentError(
        `${where}: node is not a node of this list (${describeValue(node)})`,
      )
    }
    return at
  }
 
  /** Adds a node for `element` between `prev` and `next` (neighbours, or `undefined` at an end). */
  private link(
    prev: ListNode<E> | undefined,
    next: ListNode<E> | undefined,
    element: E,
  ): ListNode<E> {
    const node = new ListNode(element, prev, next, this)
    if (prev === undefined) this.head = node
    else prev.next = node
    if (next === undefined) this.tail = node
    else next.prev = node
    this.length++
    this.changes.structural()
    return node
  }
 
  /** Takes `node` out of the chain and cuts it loose; the caller updates `length` and counts. */
  private detach(node: ListNode<E>): void {
    const prev = node.prev
    const next = node.next
    if (prev === undefined) this.head = next
    else prev.next = next
    if (next === undefined) this.tail = prev
    else next.prev = prev
    node.next = undefined
    node.prev = undefined
    node.list = undefined
  }
}