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

import { filterInPlace } from "./_utils.ts";

/**
 * Returns all distinct elements that appear at least once in each of the given
 * arrays.
 *
 * @template T The type of the elements in the input arrays.
 *
 * @param arrays The arrays to intersect.
 *
 * @returns An array of distinct elements that appear at least once in each of
 * the given arrays.
 *
 * @example Basic usage
 * ```ts
 * import { intersect } from "@std/collections/intersect";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const lisaInterests = ["Cooking", "Music", "Hiking"];
 * const kimInterests = ["Music", "Tennis", "Cooking"];
 * const commonInterests = intersect(lisaInterests, kimInterests);
 *
 * assertEquals(commonInterests, ["Cooking", "Music"]);
 * ```
 */
export function intersect<T>(...arrays: (readonly T[])[]): T[] {
  const [originalHead, ...tail] = arrays;
  const head = [...new Set(originalHead)];
  const tailSets = tail.map((it) => new Set(it));

  for (const set of tailSets) {
    filterInPlace(head, (it) => set.has(it));
    if (head.length === 0) return head;
  }

  return head;
}

// denoCacheMetadata={"headers":{"alt-svc":"h3=\":443\"; ma=86400","cache-control":"public, max-age=31536000, immutable","vary":"Origin","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=ExnKIfY9jUMnB69ybjdVyAGHbUA35FPZSJDTfcXsmqcw9vNUJEU5oHi%2FqcueF0FYt2afs3Z%2BRZMnrSHVVLngBOOgrXuE3iKzU96xh5RMCJgvHSHfGCYmUqw%3D\"}]}","access-control-expose-headers":"*","date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","x-jsr-backend":"modules","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';","x-content-type-options":"nosniff","access-control-allow-origin":"*","etag":"\"5d12fbfb52702edf5dca8518d3b09e9b\"","content-type":"text/typescript","server":"cloudflare","set-cookie":"__cf_bm=t1i9ixffLIPdILnhKP4OtdAUWI6WrA88.HiuguylXMc-1785241874.955471-1.0.1.1-gKAvSxysBIFrJBrXcXOrNSCsteveMExbIVPeCOozww40NjRML9apdDbaT_BlGllFgirpFbPFwWl3wfoXuEV0f8Yt.4og_.8VoK5bQZ88yjaC3abLiu897GF73FiFz3rW; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cf-ray":"a223e6564f027db6-LAX","content-length":"1217"},"url":"https://jsr.io/@std/collections/0.224.2/intersect.ts","time":1785241875}