zip

import { zip } from "jsr:@ende/collections";

function

function zip<T extends unknown[]>(...iterables: { [K in keyof T]: Iterable<T[K]> }): T[]

Builds N-tuples of elements from the given N iterables with matching indices, stopping when the shortest iterable is exhausted.

Notes:

  • Inputs are consumed eagerly. Non-array iterables are materialized via Array.from before zipping, so passing an infinite iterable (such as an unbounded generator) will hang.
  • Strings are iterables of code points. Passing a string zips it character-by-character rather than treating it as a single scalar value.
...iterables: { [K in keyof T]: Iterable<T[K]> }

The iterables to zip.

Returns

A new array containing N-tuples of elements from the given iterables.

Example: Basic usage

import { zip } from "@ende/collections/zip";
import { assertEquals } from "@ende/assert";

const numbers = [1, 2, 3, 4];
const letters = ["a", "b", "c", "d"];
const pairs = zip(numbers, letters);

assertEquals(
  pairs,
  [
    [1, "a"],
    [2, "b"],
    [3, "c"],
    [4, "d"],
  ],
);

Example: With iterables

import { zip } from "@ende/collections/zip";
import { assertEquals } from "@ende/assert";

assertEquals(
  zip(new Set([1, 2, 3]), ["a", "b", "c"]),
  [[1, "a"], [2, "b"], [3, "c"]],
);

Example: Strings are iterables

import { zip } from "@ende/collections/zip";
import { assertEquals } from "@ende/assert";

// A string is zipped character-by-character, not as a single value.
assertEquals(
  zip("abc", [1, 2, 3]),
  [["a", 1], ["b", 2], ["c", 3]],
);

Source