interleave

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

function

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

Returns all elements from the given iterables in round-robin order. Unlike zip, which stops at the shortest iterable and returns tuples, interleave continues until all input iterables are exhausted and returns a flat array. All input iterables are consumed eagerly.

...iterables: { [K in keyof T]: Iterable<T[K]> }

The iterables to interleave.

Returns

A new array containing all elements from the input iterables in round-robin order.

Example: Basic usage

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

const numbers = [1, 2, 3];
const letters = ["a", "b", "c"];

assertEquals(interleave(numbers, letters), [1, "a", 2, "b", 3, "c"]);

Example: Unequal-length arrays

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

assertEquals(
  interleave([1, 2, 3], ["a", "b"], [true]),
  [1, "a", true, 2, "b", 3],
);

Example: With iterables

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

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

Source