Skip to content

Commit

Permalink
perf(replaceOrAppend): splice instead of creating 2 intermediate arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
aleclarson committed Jul 2, 2024
1 parent 0b35ae3 commit a587212
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions src/array/replaceOrAppend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,13 @@ export function replaceOrAppend<T>(
if (!array) {
return [newItem]
}
for (let idx = 0; idx < array.length; idx++) {
const item = array[idx]
if (match(item, idx)) {
return [
...array.slice(0, idx),
newItem,
...array.slice(idx + 1, array.length),
]
const out = array.slice()
for (let index = 0; index < array.length; index++) {
if (match(array[index], index)) {
out.splice(index, 1, newItem)
return out
}
}
return [...array, newItem]
out.push(newItem)
return out
}

0 comments on commit a587212

Please sign in to comment.