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
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Returns all distinct elements that appear at least once in each of the given
|
|
|
|
* arrays.
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the elements in the input arrays.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @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
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { intersect } from "@std/collections/intersect";
|
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 lisaInterests = ["Cooking", "Music", "Hiking"];
|
|
|
|
* const kimInterests = ["Music", "Tennis", "Cooking"];
|
|
|
|
* const commonInterests = intersect(lisaInterests, kimInterests);
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(commonInterests, ["Cooking", "Music"]);
|
2021-07-15 21:37:53 +00:00
|
|
|
* ```
|
|
|
|
*/
|
2021-08-12 10:10:59 +00:00
|
|
|
export function intersect<T>(...arrays: (readonly T[])[]): T[] {
|
2024-07-18 04:49:32 +00:00
|
|
|
const [array, ...otherArrays] = arrays;
|
|
|
|
let set = new Set(array);
|
|
|
|
for (const array of otherArrays) {
|
|
|
|
set = set.intersection(new Set(array));
|
|
|
|
if (set.size === 0) break;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|
2024-07-18 04:49:32 +00:00
|
|
|
return [...set];
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|