From 440b4bc6e1719421471988eecb99a2209b773010 Mon Sep 17 00:00:00 2001 From: petterive Date: Mon, 5 Aug 2019 23:41:40 +0200 Subject: [PATCH] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20avoid=20unneccessary?= =?UTF-8?q?=20iteration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/useUpsert.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/useUpsert.ts b/src/useUpsert.ts index df6fbd9369..b04d552d9a 100644 --- a/src/useUpsert.ts +++ b/src/useUpsert.ts @@ -11,18 +11,20 @@ const useUpsert = ( const [items, actions] = useList(initialList); const upsert = (upsertedItem: T) => { - const itemAlreadyExists = items.find(item => comparisonFunction(upsertedItem, item)); - if (itemAlreadyExists) { - return actions.set( - items.map(existingItem => { - if (comparisonFunction(upsertedItem, existingItem)) { - return upsertedItem; - } - return existingItem; - }) - ); + let itemWasFound = false; + for (let i = 0; i < items.length; i++) { + const existingItem = items[i]; + + const shouldUpdate = comparisonFunction(existingItem, upsertedItem); + if (shouldUpdate) { + actions.updateAt(i, upsertedItem); + itemWasFound = true; + break; + } + } + if (!itemWasFound) { + actions.push(upsertedItem); } - return actions.push(upsertedItem); }; return [