Skip to content

Commit

Permalink
refactor: 💡 avoid unneccessary iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
PetterIve committed Aug 5, 2019
1 parent 915b25a commit 440b4bc
Showing 1 changed file with 13 additions and 11 deletions.
24 changes: 13 additions & 11 deletions src/useUpsert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,20 @@ const useUpsert = <T>(
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 [
Expand Down

0 comments on commit 440b4bc

Please sign in to comment.