intersection
EditReturns distinct values shared by every provided array.
/** Returns distinct values present in every provided array. */export const intersection = <const T>( array: readonly T[], ...others: ReadonlyArray<readonly unknown[]>): T[] => { const sets = others.map((other) => { if (!Array.isArray(other)) { throw new TypeError("comparison values must be arrays"); } const set = new Set<unknown>(); for (let index = 0; index < other.length; index += 1) { if (Object.hasOwn(other, index)) set.add(other[index]); } return set; }); const seen = new Set<T>(); const result: T[] = [];
for (let index = 0; index < array.length; index += 1) { if (!Object.hasOwn(array, index)) continue; const value = array[index] as T; if (seen.has(value) || !sets.every((set) => set.has(value))) continue; seen.add(value); result.push(value); } return result;};Download
Section titled “Download”wget -O src/lib/intersection.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/intersection.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/intersection.ts" src/lib/intersection.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { intersection } from "./intersection";
const shared = intersection(["read", "write"], ["write", "delete"]);// ["write"]array(readonly T[]) — The ordered source array. Empty slots are skipped....others(readonly (readonly unknown[])[]) — Arrays that must contain each result. Empty slots are skipped, not treated asundefined, and their element types do not widen the result.- Returns distinct values in first-seen order.