From 1437d19e1a41c5e1e0753f1451b42187e2e7f6d4 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Tue, 2 Jul 2024 15:41:55 -0400 Subject: [PATCH] perf(merge): avoid arrow function in loop and avoid calling user-provided key generator more than once per item (#60) Co-authored-by: Vladimir Ivakin --- src/array/merge.ts | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/src/array/merge.ts b/src/array/merge.ts index 09f35393..87a75ec5 100644 --- a/src/array/merge.ts +++ b/src/array/merge.ts @@ -13,29 +13,25 @@ * ``` */ export function merge( - root: readonly T[], - others: readonly T[], - matcher: (item: T) => any, + prev: readonly T[], + array: readonly T[], + toKey: (item: T) => any, ): T[] { - if (!others && !root) { + if (!array && !prev) { return [] } - if (!others) { - return [...root] + if (!array) { + return [...prev] } - if (!root) { + if (!prev) { return [] } - if (!matcher) { - return [...root] + if (!toKey) { + return [...prev] } - return root.reduce((acc, r) => { - const matched = others.find(o => matcher(r) === matcher(o)) - if (matched) { - acc.push(matched) - } else { - acc.push(r) - } - return acc - }, [] as T[]) + const keys = array.map(toKey) + return prev.map((prevItem) => { + const index = keys.indexOf(toKey(prevItem)); + return index > -1 ? array[index] : prevItem; + }) }