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

100% Statements 97/97
100% Branches 26/26
100% Functions 33/33
100% Lines 81/81

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                                                                      2334325x                           825789x         5073x         4486579x         29039x         9280x       3424354x       478530x       2728x 1691x       573605x 1654399x 573596x       33323x 33323x 81x 40x   33237x 33237x 68010x 68010x 34x               834x 834x 2351x 189x 189x     645x       20x 20x 20x 10x       33076x 76322x       33366x 75479x       90952x 90952x 629154x         325x 325x 618x 618x         671x       795x       737x       990132x 990132x       442519x               738x 738x         129392x         174311x 386x       173925x 303504x 173735x         66244x 66236x 151785x   8x 20x 4x                   157755x 157755x 157755x 157755x 157755x 806003x 806003x 68x       805871x 805871x   157623x 54589x 54589x                 3296x 3296x 3296x 9299x 9299x        
// The skeleton every collection extends: everything that can be written once from a few engine
// hooks. Families override methods for speed (hash lookups, O(1) clear) or semantics (structural
// equality, extra `forEach` arguments).
 
import { ConcurrentModificationError } from '../../errors/errors'
import type { Collection, Cursor } from '../../interfaces/collection'
import { describeValue, isIterable, requireFunction } from '../checks'
import { equalsSymbol, type HashFunction, hashCodeSymbol, sameValueZero } from '../equality'
import { hashPrimitiveOrIdentity } from '../hashing'
import { apply } from '../intrinsics'
import {
  COLLECTION_BRAND,
  collectionToString,
  INSPECT,
  type InspectOptions,
  inspectCollection,
} from '../output'
import { ChangeCounter } from '../revision'
 
/**
 * Base class of every collection.
 *
 * Engines implement `size`, `[Symbol.iterator]`, `add`, `cursor` and `[Symbol.toStringTag]`, record
 * every change through `changes`, and choose an iteration mode. Everything else has a default here.
 *
 * @internal
 */
export abstract class AbstractCollection<E> implements Collection<E> {
  /**
   * The change counter: `structural()` when elements are added or removed, `replaced()` otherwise.
   * Views share the counter of the collection they show.
   */
  protected readonly changes: ChangeCounter
 
  constructor(changes?: ChangeCounter) {
    this.changes = changes === undefined ? new ChangeCounter() : changes
  }
 
  /** `fail-fast` for collections with no native counterpart, `live` for hash collections. */
  protected abstract readonly iterationMode: 'fail-fast' | 'live'
 
  abstract get size(): number
  abstract get [Symbol.toStringTag](): string
  abstract [Symbol.iterator](): IterableIterator<E>
  abstract add(element: E): this
  abstract cursor(): Cursor<E>
 
  /** The brackets `toString` and inspect use: `[]` by default, `{}` for sets. */
  protected brackets(): readonly [string, string] {
    return ['[', ']']
  }
 
  /** Element equality for `has`, `delete`, `removeAll` and `retainAll`. SameValueZero by default. */
  protected elementEquals(a: E, b: E): boolean {
    return sameValueZero(a, b)
  }
 
  /** The name that starts error messages and `toString`: the class name. */
  protected get className(): string {
    return this[Symbol.toStringTag]
  }
 
  /** `<Class>.<method>`, the label of an error; built only when an error is thrown. */
  errorLabel(method: string): string {
    return `${this.className}.${method}`
  }
 
  /** Marks every collection for `isCollection`, across loaded copies. */
  get [COLLECTION_BRAND](): true {
    return true
  }
 
  get revision(): number {
    return this.changes.revision
  }
 
  isEmpty(): boolean {
    return this.size === 0
  }
 
  has(element: E): boolean {
    for (const candidate of this) if (this.elementEquals(candidate, element)) return true
    return false
  }
 
  toArray(): E[] {
    const out: E[] = []
    for (const element of this) out.push(element)
    return out
  }
 
  forEach(action: (element: E) => void, thisArg?: unknown): void {
    this.requireFunction(action, 'forEach', 'action')
    if (this.iterationMode === 'live') {
      for (const element of this) apply(action, thisArg, [element])
      return
    }
    const expected = this.changes.structure
    for (const element of this) {
      apply(action, thisArg, [element])
      if (this.changes.structure !== expected) {
        throw new ConcurrentModificationError(
          `${this.className}.forEach: the collection was changed by the callback`,
        )
      }
    }
  }
 
  delete(element: E): boolean {
    const cursor = this.cursor()
    while (cursor.hasNext()) {
      if (this.elementEquals(cursor.next(), element)) {
        cursor.remove()
        return true
      }
    }
    return false
  }
 
  addAll(elements: Iterable<E>): boolean {
    const items = this.readAll(elements, 'addAll')
    const before = this.changes.structure
    for (const item of items) this.add(item)
    return this.changes.structure !== before
  }
 
  removeAll(elements: Iterable<E>): boolean {
    const matches = this.membership(this.readAll(elements, 'removeAll'))
    return this.removeDecided('removeAll', (element) => matches(element))
  }
 
  retainAll(elements: Iterable<E>): boolean {
    const matches = this.membership(this.readAll(elements, 'retainAll'))
    return this.removeDecided('retainAll', (element) => !matches(element))
  }
 
  removeIf(predicate: (element: E) => unknown): boolean {
    this.requireFunction(predicate, 'removeIf', 'predicate')
    return this.removeDecided('removeIf', (element) =>
      Boolean(apply(predicate, undefined, [element])),
    )
  }
 
  clear(): void {
    const cursor = this.cursor()
    while (cursor.hasNext()) {
      cursor.next()
      cursor.remove()
    }
  }
 
  equals(other: unknown): boolean {
    return other === this
  }
 
  [equalsSymbol](other: unknown): boolean {
    return this.equals(other)
  }
 
  [hashCodeSymbol](_hash: HashFunction): number {
    return hashPrimitiveOrIdentity(this)
  }
 
  toString(): string {
    const [open, close] = this.brackets()
    return collectionToString(this, open, close)
  }
 
  toJSON(): E[] {
    return this.toArray()
  }
 
  [INSPECT](
    depth: number | null,
    options: InspectOptions,
    inspect: (value: unknown, options: InspectOptions) => string,
  ): string {
    const [open, close] = this.brackets()
    return inspectCollection(this, depth, options, inspect, open, close)
  }
 
  /** Throws `TypeError` unless `value` is a function. */
  protected requireFunction(value: unknown, method: string, what: string): void {
    if (typeof value !== 'function') requireFunction(value, this.errorLabel(method), what)
  }
 
  /** Reads the whole argument into an array before any change (self, views, throwing iterables). */
  protected readAll(elements: Iterable<E>, method: string): E[] {
    if (!isIterable(elements)) {
      throw new TypeError(
        `${this.className}.${method}: elements is not iterable (${describeValue(elements)})`,
      )
    }
    const items: E[] = []
    for (const item of elements) items.push(item)
    return items
  }
 
  /** Returns a membership test against `items` under this collection's equality. */
  private membership(items: E[]): (element: E) => boolean {
    if (this.elementEquals === AbstractCollection.prototype.elementEquals) {
      const set = new Set<E>(items)
      return (element) => set.has(element)
    }
    return (element) => {
      for (const item of items) if (this.elementEquals(element, item)) return true
      return false
    }
  }
 
  /**
   * Decides every element first (user code runs only here), then removes the chosen ones through a
   * cursor. An error while deciding removes nothing; a structural change while deciding throws
   * `ConcurrentModificationError` and removes nothing.
   */
  protected removeDecided(method: string, decide: (element: E, index: number) => boolean): boolean {
    const flags: boolean[] = []
    const expected = this.changes.structure
    let any = false
    const elements = this.toArray()
    for (let i = 0; i < elements.length; i++) {
      const remove = decide(elements[i] as E, i)
      if (this.changes.structure !== expected) {
        throw new ConcurrentModificationError(
          `${this.className}.${method}: the collection was changed while deciding`,
        )
      }
      flags.push(remove)
      if (remove) any = true
    }
    if (!any) return false
    this.removeMarked(flags, method)
    return true
  }
 
  /**
   * Removes the elements whose position in iteration order is marked `true` in `flags`. The
   * default walks a cursor; collections that can compact in one pass override it. `method` names
   * the public bulk method, for error messages.
   */
  protected removeMarked(flags: readonly boolean[], _method: string): void {
    const cursor = this.cursor()
    let index = 0
    while (cursor.hasNext()) {
      cursor.next()
      if (flags[index++] === true) cursor.remove()
    }
  }
}