// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { minOf } from "./min_of.ts";

/**
 * Builds N-tuples of elements from the given N arrays with matching indices,
 * stopping when the smallest array's end is reached.
 *
 * @template T the type of the tuples produced by this function.
 *
 * @param arrays The arrays to zip.
 *
 * @returns A new array containing N-tuples of elements from the given arrays.
 *
 * @example Basic usage
 * ```ts
 * import { zip } from "@std/collections/zip";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * 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"],
 *   ],
 * );
 * ```
 */
export function zip<T extends unknown[]>(
  ...arrays: { [K in keyof T]: ReadonlyArray<T[K]> }
): T[] {
  const minLength = minOf(arrays, (element) => element.length) ?? 0;

  const result: T[] = new Array(minLength);

  for (let i = 0; i < minLength; i += 1) {
    const arr = arrays.map((it) => it[i]);
    result[i] = arr as T;
  }

  return result;
}

// denoCacheMetadata={"headers":{"content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","set-cookie":"__cf_bm=0aVBweUIfGcaM8nhI7x51ZQxyLh4_AsLDrnqAy_6dQE-1785241874.96788-1.0.1.1-gW3rnCnruNG2WRcXcXq.IaLyw_.36.L28EVtrSBP0TF8iMBNzb5rxkYW3Qmqmzgpt.fT9qUFRNIafEIcG1JZx.8t4n.1eJCGSLJ6OHLtrF6zpuTRUC1P5Ug1qWYYvylp; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","vary":"Origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cross-origin-resource-policy":"cross-origin","server":"cloudflare","cf-ray":"a223e6564f4c7db6-LAX","x-robots-tag":"noindex","date":"Tue, 28 Jul 2026 12:31:15 GMT","x-jsr-backend":"modules","access-control-allow-origin":"*","cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff","alt-svc":"h3=\":443\"; ma=86400","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=eJcaVsGTnNKwcgGiyHZMYUbB1xbA4Q32Nje2k0tBBkcGrFE0lXjlqSeKh5xFsJMd4B0%2FiD5yaenx1raBllhz85H8KFah5oMak618VPRDdzZhjfc%2FXUQDkzw%3D\"}]}","etag":"\"306fd3fe68f287307d5a6982f7dd85df\"","content-type":"text/typescript","content-length":"1225","access-control-expose-headers":"*"},"url":"https://jsr.io/@std/collections/0.224.2/zip.ts","time":1785241875}