All files / src/internal/skeletons abstract-list.ts

100% Statements 169/169
100% Branches 52/52
100% Functions 47/47
100% Lines 139/139

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                                        105x 105x                             372032x                           1678x               1831x         663233x         116x         4440x           64324x       50079x 50046x       55x 55x 39x       11188x 97577x 8969x       38467x 1432x       7411x       114830x 114830x 364341x 114826x           1165x 1165x       773x 773x       12x 12x       832x 832x       657x 657x 657x 657x 657x 657x 1x       639x 628x 628x       64x 64x 64x 21x 21x       378022x 378022x 378022x 378022x       3311x       25x 14x       1226x 1226x 1202x       2142x 2142x 942x 942x       479x 479x       63x 63x       53x 53x       1304x 1304x 1304x 1304x 27741x           104x 104x 911x 104x 104x       24x 24x 24x 24x 24x 46x 46x 3x       39x         1720x 1720x 1720x 1714x 1714x 1677x   1677x 125998x 56893x 1677x 182859x 4x     49973x   1678x 1678x                 100x 100x 100x 100x 100x 177x 177x 16x               212687x 212687x       1111x 1111x       243x 243x 243x 243x                   76886x           108144x 108144x 108067x 107827x 107827x 107827x 107558x   30x   107528x 107528x 109592x 121x   108063x   105998x           109207x   11x   109196x 109196x 109439x 107717x           80x      
// The skeleton every list extends: every `List` operation written once over six index operations,
// which the array engine implements on its array and the views implement by mapping indexes onto
// the list they show.
 
import { ConcurrentModificationError, NoSuchElementError } from '../../errors/errors'
import type { Comparator } from '../../functions/comparators'
import type { List, ListCursor } from '../../interfaces/list'
import { isBranded, LIST_BRAND, SEQUENCED_COLLECTION_BRAND } from '../brand'
import { checkIndex, checkPosition, checkRange } from '../checks'
import { guardedCompare } from '../compare'
import { createGuard } from '../cycle'
import { equalsAt, type HashFunction, hashCodeSymbol, sameValueZero } from '../equality'
import { apply, imul } from '../intrinsics'
import { type IndexedList, IndexIterator, IndexListCursor } from '../list-iteration'
import { compareNatural } from '../natural-order'
import type { ChangeCounter } from '../revision'
import { stableSort } from '../sort'
import { AbstractCollection } from './abstract-collection'
 
// One guard per operation, so an element's own code can compare or hash a list mid-operation.
const equalsGuard = /*#__PURE__*/ createGuard()
const hashGuard = /*#__PURE__*/ createGuard()
 
/**
 * Base class of every list and list view.
 *
 * Subclasses implement `size`, `[Symbol.toStringTag]` and the six index operations (`getAt`,
 * `setAt`, `insertAt`, `insertItems`, `removeAtIndex`, `removeRange`), each recording its change
 * in the shared counter. Indexes reaching them are already checked.
 *
 * @internal
 */
export abstract class AbstractList<E>
  extends AbstractCollection<E>
  implements List<E>, IndexedList<E>
{
  protected readonly iterationMode = 'fail-fast' as const
 
  abstract getAt(index: number): E
  abstract setAt(index: number, element: E): void
  abstract insertAt(index: number, element: E): void
  abstract insertItems(index: number, elements: readonly E[]): void
  abstract removeAtIndex(index: number): E
  abstract removeRange(from: number, to: number): void
 
  /**
   * Records a structural change that moved elements without adding or removing any (a sort).
   * Views pass it to the list they show and refresh their own state.
   */
  markStructural(): void {
    this.changes.structural()
  }
 
  /** Throws when the list can no longer be used (a stale view). Lists that never go stale pass. */
  assertUsable(): void {}
 
  /** The list handed to callbacks as `list` and returned by `reversed().reversed()`: the public object the caller holds. */
  get owner(): List<E> {
    return this
  }
 
  /** The change counter, shared with the views of this list. */
  get changeCounter(): ChangeCounter {
    return this.changes
  }
 
  /** Marks every list for `isSequencedCollection`, across loaded copies. */
  get [SEQUENCED_COLLECTION_BRAND](): true {
    return true
  }
 
  /** Marks every list for `isList`, across loaded copies. */
  get [LIST_BRAND](): true {
    return true
  }
 
  // ── Reading ──
 
  get(index: number): E {
    return this.getAt(checkIndex(index, this.size, this, 'get'))
  }
 
  getFirst(): E {
    if (this.size === 0) throw this.empty('getFirst')
    return this.getAt(0)
  }
 
  getLast(): E {
    const size = this.size
    if (size === 0) throw this.empty('getLast')
    return this.getAt(size - 1)
  }
 
  indexOf(element: E): number {
    const size = this.size
    for (let i = 0; i < size; i++) if (sameValueZero(this.getAt(i), element)) return i
    return -1
  }
 
  lastIndexOf(element: E): number {
    for (let i = this.size - 1; i >= 0; i--) if (sameValueZero(this.getAt(i), element)) return i
    return -1
  }
 
  override has(element: E): boolean {
    return this.indexOf(element) >= 0
  }
 
  override toArray(): E[] {
    const size = this.size
    const out: E[] = []
    for (let i = 0; i < size; i++) out.push(this.getAt(i))
    return out
  }
 
  // ── Changing ──
 
  add(element: E): this {
    this.insertAt(this.size, element)
    return this
  }
 
  addFirst(element: E): this {
    this.insertAt(0, element)
    return this
  }
 
  addLast(element: E): this {
    this.insertAt(this.size, element)
    return this
  }
 
  insert(index: number, element: E): this {
    this.insertAt(checkPosition(index, this.size, this, 'insert'), element)
    return this
  }
 
  insertAll(index: number, elements: Iterable<E>): boolean {
    this.assertUsable()
    const where = 'insertAll'
    const position = checkPosition(index, this.size, `${this.className}.${where}`)
    const before = this.changes.structure
    const items = this.readAll(elements, where)
    if (this.changes.structure !== before) {
      throw new ConcurrentModificationError(
        `${this.className}.${where}: the list was changed while elements were read`,
      )
    }
    if (items.length === 0) return false
    this.insertItems(position, items)
    return true
  }
 
  override addAll(elements: Iterable<E>): boolean {
    this.assertUsable()
    const items = this.readAll(elements, 'addAll')
    if (items.length === 0) return false
    this.insertItems(this.size, items)
    return true
  }
 
  set(index: number, element: E): E {
    const i = checkIndex(index, this.size, this, 'set')
    const old = this.getAt(i)
    this.setAt(i, element)
    return old
  }
 
  removeAt(index: number): E {
    return this.removeAtIndex(checkIndex(index, this.size, this, 'removeAt'))
  }
 
  removeFirst(): E {
    if (this.size === 0) throw this.empty('removeFirst')
    return this.removeAtIndex(0)
  }
 
  removeLast(): E {
    const size = this.size
    if (size === 0) throw this.empty('removeLast')
    return this.removeAtIndex(size - 1)
  }
 
  override delete(element: E): boolean {
    const index = this.indexOf(element)
    if (index < 0) return false
    this.removeAtIndex(index)
    return true
  }
 
  override clear(): void {
    const size = this.size
    if (size > 0) this.removeRange(0, size)
  }
 
  override removeAll(elements: Iterable<E>): boolean {
    this.assertUsable()
    return super.removeAll(elements)
  }
 
  override retainAll(elements: Iterable<E>): boolean {
    this.assertUsable()
    return super.retainAll(elements)
  }
 
  override removeIf(predicate: (element: E, index: number, list: List<E>) => unknown): boolean {
    this.assertUsable()
    this.requireFunction(predicate, 'removeIf', 'predicate')
    const list = this.owner
    return this.removeDecided('removeIf', (element, index) =>
      Boolean(apply(predicate, undefined, [element, index, list])),
    )
  }
 
  /** Keeps the unmarked elements in order, through two index operations (one pass each). */
  protected override removeMarked(flags: readonly boolean[]): void {
    const size = this.size
    const kept: E[] = []
    for (let i = 0; i < size; i++) if (flags[i] !== true) kept.push(this.getAt(i))
    this.removeRange(0, size)
    if (kept.length > 0) this.insertItems(0, kept)
  }
 
  replaceAll(op: (element: E, index: number, list: List<E>) => E): void {
    this.assertUsable()
    this.requireFunction(op, 'replaceAll', 'op')
    const list = this.owner
    const expected = this.changes.structure
    for (let i = 0; i < this.size; i++) {
      const value = apply(op, undefined, [this.getAt(i), i, list]) as E
      if (this.changes.structure !== expected) {
        throw new ConcurrentModificationError(
          `${this.className}.replaceAll: the list was changed by op`,
        )
      }
      this.setAt(i, value)
    }
  }
 
  sort(comparator?: Comparator<E>): this {
    this.assertUsable()
    const where = `${this.className}.sort`
    if (comparator !== undefined) this.requireFunction(comparator, 'sort', 'comparator')
    const items = this.toArray()
    if (items.length >= 2) {
      const expected = this.changes.structure
      const compare =
        comparator === undefined
          ? (a: E, b: E) => compareNatural(a, b, where)
          : (a: E, b: E) => guardedCompare(comparator, a, b, where)
      const sorted = stableSort(items, compare, () => {
        if (this.changes.structure !== expected) {
          throw new ConcurrentModificationError(`${where}: the list was changed by the comparator`)
        }
      })
      for (let i = 0; i < sorted.length; i++) this.setAt(i, sorted[i] as E)
    }
    this.markStructural()
    return this
  }
 
  // ── Iteration ──
 
  override forEach(
    action: (element: E, index: number, list: List<E>) => void,
    thisArg?: unknown,
  ): void {
    this.assertUsable()
    this.requireFunction(action, 'forEach', 'action')
    const list = this.owner
    const expected = this.changes.structure
    for (let i = 0; i < this.size; i++) {
      apply(action, thisArg, [this.getAt(i), i, list])
      if (this.changes.structure !== expected) {
        throw new ConcurrentModificationError(
          `${this.className}.forEach: the collection was changed by the callback`,
        )
      }
    }
  }
 
  [Symbol.iterator](): IterableIterator<E> {
    this.assertUsable()
    return new IndexIterator(this, this.changes, `${this.className}[Symbol.iterator]().next`)
  }
 
  cursor(): ListCursor<E> {
    this.assertUsable()
    return new IndexListCursor(this, this.changes, 0, `${this.className}.cursor`)
  }
 
  listCursor(index?: number): ListCursor<E> {
    const where = `${this.className}.listCursor`
    const position = index === undefined ? 0 : checkPosition(index, this.size, where)
    this.assertUsable()
    return new IndexListCursor(this, this.changes, position, where)
  }
 
  // ── Views ──
 
  abstract subList(from: number, to: number): List<E>
  abstract reversed(): List<E>
 
  /** Checks a `subList` range against this list; views are built by the subclass. */
  protected checkSubList(from: number, to: number): void {
    checkRange(from, to, this.size, `${this.className}.subList`)
  }
 
  // ── Equality and hashing ──
 
  override equals(other: unknown): boolean {
    this.assertUsable()
    if (other === this || other === this.owner) return true
    if (!isBranded(other, LIST_BRAND)) return false
    const size = this.size
    const that = other as List<unknown>
    if (that.size !== size) return false
    return equalsGuard(
      this,
      () => false,
      () => {
        let i = 0
        for (const element of that) {
          if (i >= size || !equalsAt(this.getAt(i), element, `${this.className}.equals`)) {
            return false
          }
          i++
        }
        return i === size
      },
    )
  }
 
  override [hashCodeSymbol](hash: HashFunction): number {
    return hashGuard(
      this,
      () => 0,
      () => {
        let h = 1
        const size = this.size
        for (let i = 0; i < size; i++) h = (imul(31, h) + hash(this.getAt(i))) | 0
        return h
      },
    )
  }
 
  private empty(method: string): NoSuchElementError {
    return new NoSuchElementError(`${this.className}.${method}: the list is empty`)
  }
}