From 99085ec17e992b81ffdc6168302037c7d2e47659 Mon Sep 17 00:00:00 2001 From: Alec Larson <1925840+aleclarson@users.noreply.github.com> Date: Tue, 2 Jul 2024 13:17:57 -0400 Subject: [PATCH] perf(replaceOrAppend): splice instead of creating 2 intermediate arrays --- src/array/replaceOrAppend.ts | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/array/replaceOrAppend.ts b/src/array/replaceOrAppend.ts index b9ad4e22f..b5584f180 100644 --- a/src/array/replaceOrAppend.ts +++ b/src/array/replaceOrAppend.ts @@ -25,15 +25,13 @@ export function replaceOrAppend( 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 }