Skip to main content
Module

x/aitertools/mod.ts>toMap

Well-tested utility functions dealing with async iterables
Go to Latest
function toMap
import { toMap } from "https://deno.land/x/aitertools@0.5.0/mod.ts";

Creates a map from an async iterable of key-value pairs. Each pair is represented as an array of two elements.

import { toMap } from "./collections.ts";

async function* gen(): AsyncIterableIterator<[string, number]> {
  yield ["foo", 1]; yield ["bar", 2]; yield ["baz", 3]; yield ["qux", 4];
}
const map = await toMap<string, number>(gen());

The map variable will be a map like Map { "foo" => 1, "bar" => 2, "baz" => 3, "qux" => 4 }.

Duplicate keys are removed except for the last occurrence of each key. E.g.:

import { fromIterable, toMap } from "./collections.ts";

const iterable = fromIterable<[string, number]>([
  ["foo", 1], ["bar", 2], ["baz", 3], ["qux", 4],
  ["foo", 5], ["bar", 6],
]);
const map = await toMap<string, number>(iterable);

The map variable will be a map like Map { "foo" => 5, "bar" => 6, "baz" => 3, "qux" => 4 }.

Note that the iterable source is assumed to be finite; otherwise, it will never return. The following example will never return:

import { toMap } from "./collections.ts";
import { count } from "./infinite.ts";
import { map } from "./map.ts";

await toMap<number, number>(
  map((v: number) => [v, v] as [number, number], count(0))
);

Type Parameters

K

The type of the keys in the source and the returned map.

V

The type of the values in the source and the returned map.

Parameters

source: AsyncIterable<[K, V]>

An async iterable of key-value pairs to create a map from. Each pair is represented as an array of two elements. It must be finite.

Returns

Promise<Map<K, V>>

A map that contains the key-value pairs from the source iterable. Duplicate keys are removed except for the last one.