2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-07-15 21:37:53 +00:00
|
|
|
|
2023-11-20 00:04:19 +00:00
|
|
|
import { minOf } from "./min_of.ts";
|
|
|
|
|
2021-07-15 21:37:53 +00:00
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Builds N-tuples of elements from the given N arrays with matching indices,
|
|
|
|
* stopping when the smallest array's end is reached.
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T the type of the tuples produced by this function.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param arrays The arrays to zip.
|
|
|
|
*
|
|
|
|
* @returns A new array containing N-tuples of elements from the given arrays.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { zip } from "@std/collections/zip";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-07-30 14:49:46 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const numbers = [1, 2, 3, 4];
|
|
|
|
* const letters = ["a", "b", "c", "d"];
|
2021-11-12 02:51:25 +00:00
|
|
|
* const pairs = zip(numbers, letters);
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(
|
|
|
|
* pairs,
|
|
|
|
* [
|
|
|
|
* [1, "a"],
|
|
|
|
* [2, "b"],
|
|
|
|
* [3, "c"],
|
|
|
|
* [4, "d"],
|
|
|
|
* ],
|
|
|
|
* );
|
2021-07-15 21:37:53 +00:00
|
|
|
* ```
|
|
|
|
*/
|
2021-11-12 02:51:25 +00:00
|
|
|
export function zip<T extends unknown[]>(
|
2023-09-21 10:18:57 +00:00
|
|
|
...arrays: { [K in keyof T]: ReadonlyArray<T[K]> }
|
2021-11-12 02:51:25 +00:00
|
|
|
): T[] {
|
2024-05-07 07:11:55 +00:00
|
|
|
const minLength = minOf(arrays, (element) => element.length) ?? 0;
|
2021-11-12 02:51:25 +00:00
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
const result: T[] = new Array(minLength);
|
2021-07-15 21:37:53 +00:00
|
|
|
|
2021-11-12 02:51:25 +00:00
|
|
|
for (let i = 0; i < minLength; i += 1) {
|
|
|
|
const arr = arrays.map((it) => it[i]);
|
2024-05-07 07:11:55 +00:00
|
|
|
result[i] = arr as T;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
return result;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|