std/collections/intersect.ts

36 lines
1.1 KiB
TypeScript
Raw Normal View History

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/**
2022-11-25 11:40:23 +00:00
* Returns all distinct elements that appear at least once in each of the given
* arrays.
*
* @typeParam 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";
*
2022-11-25 11:40:23 +00:00
* const lisaInterests = ["Cooking", "Music", "Hiking"];
* const kimInterests = ["Music", "Tennis", "Cooking"];
* const commonInterests = intersect(lisaInterests, kimInterests);
*
2022-11-25 11:40:23 +00:00
* assertEquals(commonInterests, ["Cooking", "Music"]);
* ```
*/
export function intersect<T>(...arrays: (readonly T[])[]): T[] {
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;
}
return [...set];
}