From 786692ac0f0093f3bb0873db4081cdfa7d906929 Mon Sep 17 00:00:00 2001 From: Sujan Tamang Date: Fri, 30 Sep 2022 09:05:44 +0545 Subject: [PATCH] feat(lib): add new partialUpdateMany function --- src/index.tsx | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/index.tsx b/src/index.tsx index 76d304d..a5d389b 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -59,6 +59,33 @@ export const useComplexState = >(initialValue: T[]) => { }); }; + const partialUpdateMany = (data: Partial, indexes: number[]) => { + if (typeof data !== "object") { + return; + } + + const filteredValidIndexes = indexes.filter( + (index) => !isInvalidOrNegativeIndex(index, complexState) + ); + + if (!filteredValidIndexes.length) { + return; + } + + setComplexState((prevState) => { + const newClonedComplexState = cloneDeep(prevState); + + filteredValidIndexes.forEach((index) => { + newClonedComplexState[index] = { + ...newClonedComplexState[index], + ...data, + }; + }); + + return newClonedComplexState; + }); + }; + const remove = (index: number) => { if (isInvalidOrNegativeIndex(index, complexState)) { return; @@ -74,6 +101,10 @@ export const useComplexState = >(initialValue: T[]) => { (index) => !isInvalidOrNegativeIndex(index, complexState) ); + if (!filteredValidIndexes.length) { + return; + } + setComplexState((prevState) => { return prevState.filter((_, idx) => !filteredValidIndexes.includes(idx)); }); @@ -86,6 +117,7 @@ export const useComplexState = >(initialValue: T[]) => { insertMany, update, partialUpdate, + partialUpdateMany, remove, removeMany, };