Skip to content

Commit

Permalink
perf(merge): avoid arrow function in loop and avoid calling user-prov…
Browse files Browse the repository at this point in the history
…ided key generator more than once per item
  • Loading branch information
aleclarson committed Jul 2, 2024
1 parent a639b48 commit 70358d9
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions src/array/merge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,29 +13,26 @@
* ```
*/
export function merge<T>(
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
const keys = array.map(toKey)
return prev.reduce((next, prevItem) => {
const index = keys.indexOf(toKey(prevItem))
next.push(index > -1 ? array[index] : prevItem)
return next
}, [] as T[])
}

0 comments on commit 70358d9

Please sign in to comment.