jwidget/MapUtils

Various utilities for Map.

Consumption

import * as MapUtils from "jwidget/MapUtils";

map#

<K, T, U>(map: Iterable<readonly [K, T]>, callback: (value: T, key: K) => U): Map<K, U>

map
Map.
callback
Mapping function.
returns
Mapped map.

Builds a new map of results of callback function call for each map entry with the same keys.

filter#

<K, V>(map: Iterable<readonly [K, V]>, callback: (value: V, key: K) => boolean): Map<K, V>

map
Map.
callback
Criteria callback.
returns
Filtered map.

Builds a new map of map entries the callback function returns a truthy value for.

getIterableKeys#

<K, V>(map: Iterable<readonly [K, V]>): Iterable<K>

map
Map.
returns
Map keys.

Returns an Iterable of all map keys. As opposed to native Map.keys, returns an Iterable instead of IterableIterator, so it is stateless and can be reused multiple times to iterate over the map keys.

function pushAndLog<T>(array: T[], values: Iterable<T>) {
    array.push(...values);
    for (const value of values) {
        console.log(value);
    }
}

const array: T[] = [];
const map = new Map([["a", 1], ["b", 2]]);
pushAndLog(array, map.keys()); // wrong: the values will be pushed, but not logged
pushAndLog(array, getIterableKeys(map)); // correct

getIterableValues#

<K, V>(map: Iterable<readonly [K, V]>): Iterable<V>

map
Map.
returns
Map values.

Returns an Iterable of all map values. As opposed to native Map.values, returns an Iterable instead of IterableIterator, so it is stateless and can be reused multiple times to iterate over the map values.

function pushAndLog<T>(array: T[], values: Iterable<T>) {
    array.push(...values);
    for (const value of values) {
        console.log(value);
    }
}

const array: T[] = [];
const map = new Map([["a", 1], ["b", 2]]);
pushAndLog(array, map.values()); // wrong: the values will be pushed, but not logged
pushAndLog(array, getIterableValues(map)); // correct