All files / collections / unstable_intersect.ts

100.00% Branches 5/5
100.00% Lines 10/10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x2
x26
x26
x26
x26
x53
x53
x53
x120
x26




































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * Returns all distinct elements that appear at least once in each of the given
 * iterables.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @typeParam T The type of the elements in the input iterables.
 *
 * @param iterables The iterables to intersect.
 *
 * @returns An array of distinct elements that appear at least once in each of
 * the given iterables.
 *
 * @example Basic usage
 * ```ts
 * import { intersect } from "@std/collections/unstable-intersect";
 * import { assertEquals } from "@std/assert";
 *
 * const lisaInterests = ["Cooking", "Music", "Hiking"];
 * const kimInterests = ["Music", "Tennis", "Cooking"];
 * const commonInterests = intersect(lisaInterests, kimInterests);
 *
 * assertEquals(commonInterests, ["Cooking", "Music"]);
 * ```
 */
export function intersect<T>(...iterables: Iterable<T>[]): T[] {
  const [iterable, ...otherIterables] = iterables;
  let set = new Set(iterable);
  if (set.size === 0) return [];
  for (const iterable of otherIterables) {
    set = set.intersection(new Set(iterable));
    if (set.size === 0) return [];
  }
  return [...set];
}