Skip to content

Commit

Permalink
perf(differenceBy): Optimize differenceBy (#28)
Browse files Browse the repository at this point in the history
* fix(differenceBy): make differenceBy fast

* Update src/array/differenceBy.ts

---------

Co-authored-by: Sojin Park <[email protected]>
  • Loading branch information
po4tion and raon0211 authored Jun 8, 2024
1 parent 4ec747e commit fa22ab1
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/array/differenceBy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@
* mapped identity in the second array.
*
* @example
* * const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
* const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }];
* const array2 = [{ id: 2 }, { id: 4 }];
* const mapper = item => item.id;
* const result = differenceBy(array1, array2, mapper);
* // result will be [{ id: 1 }, { id: 3 }] since the elements with id 2 are in both arrays and are excluded from the result.
*/
export function differenceBy<T, U>(firstArr: T[], secondArr: T[], mapper: (value: T) => U): T[] {
const mappedSecondArr = secondArr.map(item => mapper(item));
const mappedSecondSet = new Set(secondArr.map(item => mapper(item)));

return firstArr.filter(item => {
return !mappedSecondArr.includes(mapper(item));
return !mappedSecondSet.has(mapper(item));
});
}

0 comments on commit fa22ab1

Please sign in to comment.