Skip to content

Commit

Permalink
improved intersection performance (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
kubikowski authored Nov 11, 2022
1 parent aad40e8 commit 0d5e243
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/operations/intersection.function.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,19 @@ export function intersection<T>(...sets: ReadonlySet<T>[]): ReadonlySet<T>;
* @description A ∩ B ≔ { x : (x ∈ A) ∧ (x ∈ B) }
*/
export function intersection<T, S extends ReadonlySet<T>>(...sets: S[]): S {
const resultSet = new Set<T>(sets.shift());
if (sets.length < 2) {
return new Set<T>(sets.shift()) as ReadonlySet<T> as S;
}

const resultSet = new Set<T>();
const primarySet = sets.shift()!;
const secondarySet = sets.shift()!;

for (const element of primarySet) {
if (secondarySet.has(element)) {
resultSet.add(element);
}
}

for (const set of sets) {
for (const element of resultSet) {
Expand Down

0 comments on commit 0d5e243

Please sign in to comment.