Last active
December 21, 2021 14:17
-
-
Save T99/9d0facf01326215a408bf7f2867b1192 to your computer and use it in GitHub Desktop.
Simple Intersection Function in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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