Skip to content

Instantly share code, notes, and snippets.

@T99
Last active December 21, 2021 14:17
Show Gist options
  • Save T99/9d0facf01326215a408bf7f2867b1192 to your computer and use it in GitHub Desktop.
Save T99/9d0facf01326215a408bf7f2867b1192 to your computer and use it in GitHub Desktop.
Simple Intersection Function in Typescript
/*
* Created by Trevor Sears <[email protected]> (https://trevorsears.com/).
* 9:05 AM -- December 21st, 2021
*/
/**
* Returns an array representing the intersection between all of the provided input sets.
*
* @param {Iterable<T>} sets The sets for which an intersection subset should be generated.
* @returns {T[]} An array representing the intersection between all of the provided input sets.
*/
export function intersection<T>(...sets: Iterable<T>[]): T[] {
if (sets.length >= 1) {
let result: T[] = [...(sets.pop() as Iterable<T>)];
// De-dupe the base array.
result = Array.from(new Set(result));
for (let set of sets) {
let array: T[] = Array.from(set);
result = result.filter((value: T): boolean => array.includes(value));
}
return result;
} else return [];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment