Class HashMap<K, V, R>

Hash-based map. Supports object keys and custom hashing; offers O(1) average set/get/has.

Time O(1), Space O(1)

// should maintain insertion order
const linkedHashMap = new LinkedHashMap<number, string>();
linkedHashMap.set(1, 'A');
linkedHashMap.set(2, 'B');
linkedHashMap.set(3, 'C');

const result = Array.from(linkedHashMap);
console.log(result); // [
// [1, 'A'],
// [2, 'B'],
// [3, 'C']
// ];
// basic HashMap creation and set operation
// Create a simple HashMap with key-value pairs
const map = new HashMap<number, string>([
[1, 'one'],
[2, 'two'],
[3, 'three']
]);

// Verify size
console.log(map.size); // 3;

// Set a new key-value pair
map.set(4, 'four');
console.log(map.size); // 4;

// Verify entries
console.log([...map.entries()]); // length: 4;
// HashMap get and has operations
const map = new HashMap<string, number>([
['apple', 1],
['banana', 2],
['cherry', 3]
]);

// Check if key exists
console.log(map.has('apple')); // true;
console.log(map.has('date')); // false;

// Get value by key
console.log(map.get('banana')); // 2;
console.log(map.get('grape')); // undefined;

// Get all keys and values
const keys = [...map.keys()];
const values = [...map.values()];
console.log(keys); // contains 'apple';
console.log(values); // contains 3;
// HashMap iteration and filter operations
const map = new HashMap<number, string>([
[1, 'Alice'],
[2, 'Bob'],
[3, 'Charlie'],
[4, 'Diana'],
[5, 'Eve']
]);

// Iterate through entries
const entries: [number, string][] = [];
for (const [key, value] of map) {
entries.push([key, value]);
}
console.log(entries); // length: 5;

// Filter operation (for iteration with collection methods)
const filtered = [...map].filter(([key]) => key > 2);
console.log(filtered.length); // 3;

// Map operation
const values = [...map.values()].map(v => v.length);
console.log(values); // contains 3; // 'Bob', 'Eve'
console.log(values); // contains 7;
// HashMap for user session caching O(1) performance
interface UserSession {
userId: number;
username: string;
loginTime: number;
lastActivity: number;
}

// HashMap provides O(1) average-case performance for set/get/delete
// Perfect for session management with fast lookups
const sessionCache = new HashMap<string, UserSession>();

// Simulate user sessions
const sessions: [string, UserSession][] = [
['session_001', { userId: 1, username: 'alice', loginTime: 1000, lastActivity: 1050 }],
['session_002', { userId: 2, username: 'bob', loginTime: 1100, lastActivity: 1150 }],
['session_003', { userId: 3, username: 'charlie', loginTime: 1200, lastActivity: 1250 }]
];

// Store sessions with O(1) insertion
for (const [token, session] of sessions) {
sessionCache.set(token, session);
}

console.log(sessionCache.size); // 3;

// Retrieve session with O(1) lookup
const userSession = sessionCache.get('session_001');
console.log(userSession?.username); // 'alice';
console.log(userSession?.userId); // 1;

// Update session with O(1) operation
if (userSession) {
userSession.lastActivity = 2000;
sessionCache.set('session_001', userSession);
}

// Check updated value
const updated = sessionCache.get('session_001');
console.log(updated?.lastActivity); // 2000;

// Cleanup: delete expired sessions
sessionCache.delete('session_002');
console.log(sessionCache.has('session_002')); // false;

// Verify remaining sessions
console.log(sessionCache.size); // 2;

// Get all active sessions
const activeCount = [...sessionCache.values()].length;
console.log(activeCount); // 2;

Type Parameters

  • K = any
  • V = any
  • R = [K, V]
    1. Key-Value Pair Storage: HashMap stores key-value pairs. Each key map to a value.
    2. Fast Lookup: It's used when you need to quickly find, insert, or delete entries based on a key.
    3. Unique Keys: Keys are unique. If you try to insert another entry with the same key, the new one will replace the old entry.
    4. Unordered Collection: HashMap does not guarantee the order of entries, and the order may change over time.

Hierarchy (view full)

Constructors

  • Create a HashMap and optionally bulk-insert entries.

    Type Parameters

    • K = any
    • V = any
    • R = [K, V]

    Parameters

    • OptionalentryOrRawElements: Iterable<[K, V] | R, any, any> = []

      Iterable of entries or raw elements to insert.

    • Optionaloptions: HashMapOptions<K, V, R>

      Options: hash function and optional record-to-entry converter.

    Returns HashMap<K, V, R>

    New HashMap instance.

    Time O(N), Space O(N)

Accessors

  • get hashFn(): ((key: K) => string)
  • Get the current hash function for non-object keys.

    Returns ((key: K) => string)

    Hash function.

      • (key): string
      • Parameters

        • key: K

        Returns string

    Time O(1), Space O(1)

  • get objMap(): Map<object, V>
  • Get the internal Map used for object/function keys.

    Returns Map<object, V>

    Map of object→value.

    Time O(1), Space O(1)

  • get size(): number
  • Get the number of distinct keys stored.

    Returns number

    Current size.

    Time O(1), Space O(1)

  • get store(): {
        [p: string]: HashMapStoreItem<K, V>;
    }
  • Get the internal store for non-object keys.

    Returns {
        [p: string]: HashMapStoreItem<K, V>;
    }

    Internal record of string→{key,value}.

    • [p: string]: HashMapStoreItem<K, V>

    Time O(1), Space O(1)

  • get toEntryFn(): undefined | ((rawElement: R) => [K, V])
  • Get the raw→entry converter function if present.

    Returns undefined | ((rawElement: R) => [K, V])

    Converter function or undefined.

    Time O(1), Space O(1)

Methods

  • (Protected) Create a like-kind instance and seed it from an iterable.

    Type Parameters

    Parameters

    • Optionalentries: Iterable<TR | [TK, TV], any, any> = []

      Iterable used to seed the new map.

    • Optionaloptions: any

      Options forwarded to the constructor.

    Returns any

    A like-kind map instance.

    Time O(N), Space O(N)

  • Delete an entry by key.

    Parameters

    • key: K

      Key to delete.

    Returns boolean

    True if the key was found and removed.

    Time O(1), Space O(1)

  • Test whether all entries satisfy the predicate.

    Parameters

    • predicate: EntryCallback<K, V, boolean>

      (key, value, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns boolean

    true if all pass; otherwise false.

    Time O(n), Space O(1)

  • Filter entries into a new map.

    Parameters

    • predicate: EntryCallback<K, V, boolean>

      Predicate (key, value, index, map) → boolean.

    • OptionalthisArg: any

      Value for this inside the predicate.

    Returns any

    A new map containing entries that satisfied the predicate.

    Time O(N), Space O(N)

  • Find the first entry that matches a predicate.

    Parameters

    • callbackfn: EntryCallback<K, V, boolean>

      (key, value, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns undefined | [K, V]

    Matching [key, value] or undefined.

    Time O(n), Space O(1)

  • Type guard: check if a raw value is a [key, value] entry.

    Parameters

    • rawElement: any

    Returns rawElement is [K, V]

    True if the value is a 2-tuple.

    Time O(1), Space O(1)

  • Map values to a new map with the same keys.

    Type Parameters

    • VM

    Parameters

    • callbackfn: EntryCallback<K, V, VM>

      Mapping function (key, value, index, map) → newValue.

    • OptionalthisArg: any

      Value for this inside the callback.

    Returns any

    A new map with transformed values.

    Time O(N), Space O(N)

  • Insert or replace a single entry.

    Parameters

    • key: K

      Key.

    • value: V

      Value.

    Returns boolean

    True when the operation succeeds.

    Time O(1), Space O(1)

  • Replace the hash function and rehash the non-object store.

    Parameters

    • fn: ((key: K) => string)

      New hash function for non-object keys.

        • (key): string
        • Parameters

          • key: K

          Returns string

    Returns this

    This map instance.

    Time O(N), Space O(N)

  • Insert many entries from an iterable.

    Parameters

    • entryOrRawElements: Iterable<[K, V] | R, any, any>

      Iterable of entries or raw elements to insert.

    Returns boolean[]

    Array of per-entry results.

    Time O(N), Space O(N)

  • Test whether any entry satisfies the predicate.

    Parameters

    • predicate: EntryCallback<K, V, boolean>

      (key, value, index, self) => boolean.

    • OptionalthisArg: any

      Optional this for callback.

    Returns boolean

    true if any passes; otherwise false.

    Time O(n), Space O(1)