All files / src/internal map-input.ts

100% Statements 11/11
100% Branches 8/8
100% Functions 1/1
100% Lines 11/11

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                                      208848x 33x   208815x 208815x 2865091x 2864819x 272x 65x 65x   207x         208607x    
// Reading the entries a map is built or filled from.
 
import type { MapEntry } from '../interfaces/map'
import { isBranded, MAP_ENTRY_BRAND } from './brand'
import { describeValue, isIterable } from './checks'
 
/**
 * Reads `entries` whole and checks every item before anything is stored: each must be an array of
 * length exactly 2 or a map entry.
 *
 * Time: O(m) for `m` items.
 *
 * @param entries - The argument as given.
 * @param where - The API to name in errors.
 * @returns The `[key, value]` pairs, in order.
 * @throws TypeError when `entries` is not iterable or an item is neither a pair nor an entry.
 * @internal
 */
export function readPairs<K, V>(entries: unknown, where: string): Array<[K, V]> {
  if (!isIterable(entries)) {
    throw new TypeError(`${where}: entries is not iterable (${describeValue(entries)})`)
  }
  const pairs: Array<[K, V]> = []
  for (const item of entries as Iterable<unknown>) {
    if (Array.isArray(item) && item.length === 2) {
      pairs.push([item[0] as K, item[1] as V])
    } else if (isBranded(item, MAP_ENTRY_BRAND)) {
      const entry = item as MapEntry<K, V>
      pairs.push([entry.key, entry.value])
    } else {
      throw new TypeError(
        `${where}: item ${pairs.length} is not a [key, value] pair or a map entry (${describeValue(item)})`,
      )
    }
  }
  return pairs
}