From fa22ab163eefb16353117f63c6f8394a332fea91 Mon Sep 17 00:00:00 2001 From: Dongkyu Kim Date: Sat, 8 Jun 2024 15:36:12 +0900 Subject: [PATCH] perf(differenceBy): Optimize `differenceBy` (#28) * fix(differenceBy): make differenceBy fast * Update src/array/differenceBy.ts --------- Co-authored-by: Sojin Park --- src/array/differenceBy.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/array/differenceBy.ts b/src/array/differenceBy.ts index 67ec26159..54853d1a0 100644 --- a/src/array/differenceBy.ts +++ b/src/array/differenceBy.ts @@ -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(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)); }); }