javascript-collections-framework
    Preparing search index...

    Class HashMap<K, V>Sealed

    A map that behaves like native Map — insertion order, SameValueZero keys (NaN is one key, -0 is stored as 0), set returning the map, live iteration — and adds keys compared by value on request, structural equals, read-modify-write helpers (getOrDefault, compute, merge, replaceAll) and live keySet(), entrySet() and valueCollection() views.

    Give a key function to treat keys with the same derived key as one key, or an equivalence (such as valueEquivalence) to decide key equality by its equals and hash. The original key objects are stored and returned. null and undefined are allowed as keys and values.

    Iteration is live, as with native Map: mappings deleted before they are reached are skipped, mappings added during iteration are visited, and nothing throws ConcurrentModificationError. Writing a value is not a structural change. Changing a key's derived key or hash while it is in the map leaves lookups for it unspecified; the mapping can still be removed through a view's cursor, removeIf, removeAll, retainAll, or clear.

    Two maps are equal when they have the same size and each maps every key of the other to an equal value, in any order. Construction input must be [key, value] arrays of length 2 or map entries. The class is not designed to be subclassed.

    const ages = new HashMap([['ann', 31]])
    ages.set('bob', 27).get('bob') // 27

    const counts = new HashMap<string, number>()
    for (const word of ['a', 'b', 'a']) counts.merge(word, 1, (n, one) => n + one)
    counts.toString() // "HashMap(2) {'a' => 2, 'b' => 1}"

    Type Parameters

    • K
    • V

    Implements

    Index
    • Creates a map holding each mapping of entries in order, later pairs replacing earlier ones for equal keys; empty when entries is omitted, undefined or null. Every item is checked before anything is stored.

      Time: O(m) average for m items, plus the key or equivalence calls.

      Type Parameters

      • K
      • V

      Parameters

      • Optionalentries: Iterable<readonly [K, V] | MapEntry<K, V>, any, any> | null

        [key, value] arrays, map entries, a native Map or another map.

      • Optionaloptions: HashMapOptions<K> | null

        key or equivalence; null means none.

      Returns HashMap<K, V>

      TypeError when entries is neither iterable nor null/undefined, when an item is not an array of length 2 or a map entry, when options is not an object, when both key and equivalence are given, when key is not a function, or when equivalence lacks an equals or hash function.

      new HashMap([['a', 1], ['b', 2]]) // HashMap(2) {'a' => 1, 'b' => 2}
      new HashMap(new Map([[1, 'one']]))
    • Creates an empty map with the given options. An object that is not iterable is read as the options, so new HashMap({ a: 1 }) is an empty map (the unknown property a is ignored).

      Time: O(1).

      Type Parameters

      • K
      • V

      Parameters

      Returns HashMap<K, V>

      TypeError when both key and equivalence are given, when key is not a function, or when equivalence lacks an equals or hash function.

      const byName = new HashMap<{ name: string }, number>({ key: (item) => item.name })
      
    • get "[HASH_MAP_BRAND]"(): true

      Marks instances of this class so instanceof recognises them across copies of the package. Its key is not exported, so the getter is not called directly. Time: O(1).

      Returns true

    • get "[MAP_COLLECTION_BRAND]"(): true

      Marks maps so isMapCollection recognises them across copies of the package. Its key is not exported, so the getter is not called directly. Time: O(1).

      Returns true

    • get "[toStringTag]"(): string

      'HashMap', for Object.prototype.toString. Time: O(1).

      Returns string

    • get revision(): number

      A number that changes when a mapping is added or removed or a value is written (even the same value), and never on a read or on a call that changes nothing. Its exact values are unspecified. Time: O(1).

      Returns number

    • get size(): number

      The number of mappings. Time: O(1).

      Returns number

    • The value-equality protocol; delegates to equals. Time: as equals.

      Parameters

      • other: unknown

      Returns boolean

    • The value-equality protocol: an order-independent combination of the mappings' hashes, the same for equal maps that use the same key function, the same equivalence, or neither. Values are unspecified. Time: O(n) plus the hash calls.

      Parameters

      Returns number

    • Node's inspect hook: HashMap(1) { 'a' => 1 } in console.log. Time: as toString.

      Parameters

      • depth: number | null
      • options: object
      • inspect: (value: unknown, options: object) => string

      Returns string

    • Returns a live iterator over a new [key, value] array per mapping, in insertion order, as entries() does: deleted mappings not yet reached are skipped, added ones are visited, and clear() ends it. new Map(hashMap) copies the map this way.

      Time: O(1) to create; O(1) per step.

      Returns IterableIterator<[K, V]>

      A new iterator.

      for (const [key, value] of map) console.log(key, value)
      
    • Removes every mapping. An open iteration ends, and mappings added afterwards are visited, as with native Map.

      Time: O(1) with an equivalence; one native clear otherwise (at most O(n)).

      Returns void

      map.clear()
      map.size // 0
    • Maps key to fn(currentValueOrUndefined, key, map), or removes the mapping when the result is undefined, and returns the result. A stored undefined reaches fn as undefined, just as absence does; use has to tell them apart.

      Time: as set, plus the call.

      Parameters

      • key: K

        The key.

      • fn: (value: V | undefined, key: K, map: MapCollection<K, V>) => V | undefined

        Computes the new value.

      Returns V | undefined

      The result of fn.

      TypeError when fn is not a function, or a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when fn adds or removes mappings; its changes stay and the call makes none of its own.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      counts.compute('a', (n) => (n ?? 0) + 1)
      
    • When key is present, maps it to fn(value, key, map), or removes the mapping when the result is undefined, and returns the result; otherwise returns undefined without calling fn.

      Time: as set, plus the call.

      Parameters

      • key: K

        The key.

      • fn: (value: V, key: K, map: MapCollection<K, V>) => V | undefined

        Computes the new value.

      Returns V | undefined

      The result of fn, or undefined.

      TypeError when fn is not a function, or a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when fn adds or removes mappings.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      stock.computeIfPresent('apple', (n) => (n > 1 ? n - 1 : undefined))
      
    • Returns whether some value is SameValueZero-equal to value.

      Time: O(n).

      Parameters

      • value: V

        The value to look for.

      Returns boolean

      true when a mapping has that value.

      new HashMap([['a', 1]]).containsValue(1) // true
      
    • Returns a new HashMap with the same mappings, order and key or equivalence, independent of this one. Stored keys and hashes are copied; no user function is called.

      Time: O(n).

      Returns HashMap<K, V>

      The copy.

      const copy = map.copy()
      copy.set('z', 0) // map is unchanged
    • Removes the mapping of key and returns whether there was one.

      Time: as set.

      Parameters

      • key: K

        The key.

      Returns boolean

      true when a mapping was removed.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      new HashMap([['a', 1]]).delete('a') // true
      
    • Returns a live iterator over a new [key, value] array per mapping, in insertion order.

      Time: O(1) to create; O(1) per step.

      Returns IterableIterator<[K, V]>

      A new iterator.

      [...new HashMap([['a', 1]]).entries()] // [['a', 1]]
      
    • Returns a live view of the mappings as entries. An entry is a member when its key is present with an equal value; removing it removes the mapping; add throws UnsupportedOperationError. Each call returns a new view.

      Time: O(1).

      Returns SetCollection<MapEntry<K, V>>

      A new view.

      for (const entry of map.entrySet()) if (entry.value < 0) entry.setValue(0)
      
    • Returns whether other is a map of the same size in which every key of this map is present with a value equal under equals, and which has no key this map lacks — whatever the order, and the same both ways round. Native Map, sets, lists and plain objects are never equal to it.

      Time: O(n) average, plus the lookups on both maps and the protocol methods.

      Parameters

      • other: unknown

        Any value.

      Returns boolean

      true when other is an equal map.

      ConcurrentModificationError when a value's equals changes the structure of other while it is compared (values are compared as equals(otherValue, thisValue)).

      new HashMap([['a', 1], ['b', 2]]).equals(new HashMap([['b', 2], ['a', 1]])) // true
      
    • Calls action(value, key, map) for each mapping in insertion order, with this set to thisArg, as native Map does. Mappings deleted before they are reached are skipped; mappings added during the loop are visited.

      Time: O(n) plus the calls.

      Parameters

      • action: (value: V, key: K, map: MapCollection<K, V>) => void

        Called with each value, its key and the map.

      • OptionalthisArg: unknown

        The this value for action.

      Returns void

      TypeError when action is not a function.

      map.forEach((value, key) => console.log(key, value))
      
    • Returns the value mapped to a key equal to key, or undefined when there is none. Use has or getOrDefault to tell a stored undefined from absence.

      Time: O(1) average, plus one key or hash call and the equals calls.

      Parameters

      • key: K

        The key to look up (-0 is read as 0).

      Returns V | undefined

      The value, or undefined.

      TypeError when key returns an object or a function, equivalence.equals returns a non-boolean or equivalence.hash a non-finite number.

      ConcurrentModificationError when a key, equals or hash function adds or removes mappings.

      new HashMap([['a', 1]]).get('a') // 1
      
    • Returns the value mapped to key when the key is present (even when that value is undefined), and fallback otherwise.

      Time: as get.

      Type Parameters

      • D

      Parameters

      • key: K

        The key to look up.

      • fallback: D

        The value to return when the key is absent.

      Returns V | D

      The mapped value, or fallback.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      new HashMap([['a', 1]]).getOrDefault('b', 0) // 0
      
    • Returns the value of key when present; otherwise maps key to value and returns value, as native Map.prototype.getOrInsert does.

      Time: as set.

      Parameters

      • key: K

        The key.

      • value: V

        The value to insert when the key is absent.

      Returns V

      The mapped value.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      groups.getOrInsert('a', []).push(1)
      
    • Returns the value of key when present, without calling fn; otherwise calls fn(key), maps key to its result and returns it, as native Map.prototype.getOrInsertComputed does. If fn inserted the key itself, that mapping's value is overwritten in place; fn may change the map without an error.

      Time: as set, plus the call.

      Parameters

      • key: K

        The key.

      • fn: (key: K) => V

        Computes the value to insert, called with this undefined.

      Returns V

      The mapped value.

      TypeError when fn is not a function (even when the key is present), or a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when a key, equals or hash function adds or removes mappings.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      cache.getOrInsertComputed(id, (id) => load(id))
      
    • Returns whether a key equal to key is present.

      Time: as get.

      Parameters

      • key: K

        The key to look for.

      Returns boolean

      true when the key is present.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      new HashMap([[Number.NaN, 1]]).has(Number.NaN) // true
      
    • Returns whether the map has no mappings.

      Time: O(1).

      Returns boolean

      size === 0.

      new HashMap().isEmpty() // true
      
    • Returns a live iterator over the keys in insertion order.

      Time: O(1) to create; O(1) per step.

      Returns IterableIterator<K>

      A new iterator.

      [...new HashMap([['a', 1]]).keys()] // ['a']
      
    • Returns a live view of the keys, under this map's key equality. Removing a key removes its mapping; add throws UnsupportedOperationError. Each call returns a new view.

      Time: O(1).

      Returns SetCollection<K>

      A new view.

      map.keySet().retainAll(['a', 'b']) // keeps only the mappings of 'a' and 'b'
      
    • Maps key to value when it is absent (even when value is undefined); otherwise to fn(old, value, key, map), removing the mapping when that result is undefined. Returns the stored value, or undefined when the mapping was removed.

      Time: as set, plus the call.

      Parameters

      • key: K

        The key.

      • value: V

        The value to store, or to combine with the present one.

      • fn: (old: V, value: V, key: K, map: MapCollection<K, V>) => V | undefined

        Combines the present value with value.

      Returns V | undefined

      The stored value, or undefined.

      TypeError when fn is not a function, or a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when fn adds or removes mappings.

      Error whatever fn throws; the call inserts and changes nothing, and changes fn made stay.

      for (const word of words) counts.merge(word, 1, (n, one) => n + one)
      
    • Maps key to value, as set does, and returns the previous value, or undefined when the key was absent.

      Time: as set.

      Parameters

      • key: K

        The key.

      • value: V

        The value.

      Returns V | undefined

      The previous value, or undefined.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      new HashMap([['a', 1]]).put('a', 2) // 1
      
    • Sets every mapping of entries in order, later ones replacing earlier ones for equal keys. The whole argument is read and checked first, so map.putAll(map) is safe; mappings set before a key or hash error stay.

      Time: O(m) average for m items, plus the calls.

      Parameters

      • entries: Iterable<readonly [K, V] | MapEntry<K, V>>

        [key, value] arrays, map entries, a native Map or a map.

      Returns void

      TypeError when entries is not iterable, an item is not an array of length 2 or a map entry, or a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      map.putAll(new Map([['a', 1], ['b', 2]]))
      
    • Removes the mapping of key and returns its value, or undefined when there was none.

      Time: as set.

      Parameters

      • key: K

        The key.

      Returns V | undefined

      The removed value, or undefined.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      new HashMap([['a', 1]]).remove('a') // 1
      
    • Replaces the value of key only when the key is present, and returns the previous value, or undefined.

      Time: as set.

      Parameters

      • key: K

        The key.

      • value: V

        The new value.

      Returns V | undefined

      The previous value, or undefined.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings.

      new HashMap([['a', 1]]).replace('b', 2) // undefined; nothing is added
      
    • Replaces each value with fn(value, key, map), in iteration order. Values replaced before an error stay.

      Time: O(n) plus the calls.

      Parameters

      Returns void

      TypeError when fn is not a function.

      ConcurrentModificationError when fn adds or removes mappings.

      prices.replaceAll((price) => price * 2)
      
    • Maps key to value and returns the map, so calls chain. When an equal key is present, its stored key object and position are kept and only the value is replaced.

      Time: O(1) average, plus one key or hash call and the equals calls.

      Parameters

      • key: K

        The key (-0 is stored as 0).

      • value: V

        The value.

      Returns this

      The map.

      TypeError when a key, equals or hash function returns an invalid result.

      ConcurrentModificationError when such a function adds or removes mappings; the map keeps those changes and stores nothing itself.

      new HashMap<string, number>().set('a', 1).set('b', 2) // HashMap(2) {'a' => 1, 'b' => 2}
      
    • Returns a new array of [key, value] arrays in insertion order, so JSON.stringify writes the map as pairs (a native Map is written as {}).

      Time: O(n).

      Returns [K, V][]

      A new array.

      JSON.stringify(new HashMap([['a', 1]])) // '[["a",1]]'
      
    • Returns the class name, size and mappings in insertion order, e.g. HashMap(2) {'a' => 1, 'b' => 2}; a map that contains itself prints as [Circular].

      Time: O(length of the output) for flat contents.

      Returns string

      The text.

      String(new HashMap([['a', 1]])) // "HashMap(1) {'a' => 1}"
      
    • Returns a live view of the values, compared with SameValueZero. delete(v) removes the first mapping with that value; removeAll, retainAll and removeIf every matching mapping; add throws UnsupportedOperationError. The view equals only itself. Each call returns a new view.

      Time: O(1).

      Returns Collection<V>

      A new view.

      map.valueCollection().removeIf((v) => v === 0)
      
    • Returns a live iterator over the values in insertion order.

      Time: O(1) to create; O(1) per step.

      Returns IterableIterator<V>

      A new iterator.

      [...new HashMap([['a', 1]]).values()] // [1]
      
    • Returns whether value is a HashMap, including one created by another copy of the library with the same major version.

      Time: O(1).

      Parameters

      • value: unknown

        The value on the left of instanceof.

      Returns boolean

      true when value is a HashMap.

      new HashMap() instanceof HashMap // true
      
    • Returns a new map of the mappings of entries, in order, later pairs replacing earlier ones, with the given options. Every item is checked before anything is stored.

      Time: O(m) average for m items, plus the key or equivalence calls.

      Type Parameters

      • K
      • V

      Parameters

      • entries: Iterable<readonly [K, V] | MapEntry<K, V>>

        [key, value] arrays, map entries, a native Map or another map.

      • Optionaloptions: HashMapOptions<K> | null

        key or equivalence; null means none.

      Returns HashMap<K, V>

      A new map.

      TypeError when entries is not iterable (null and undefined included), an item is not a pair or an entry, or the options are invalid (as for the constructor).

      HashMap.from(Object.entries({ a: 1, b: 2 })) // HashMap(2) {'a' => 1, 'b' => 2}