Skip to content

Commit

Permalink
feat(lib): add new partialUpdateMany function
Browse files Browse the repository at this point in the history
  • Loading branch information
Suzan-Dev committed Sep 30, 2022
1 parent 8508fe5 commit 786692a
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,33 @@ export const useComplexState = <T extends Partial<T>>(initialValue: T[]) => {
});
};

const partialUpdateMany = (data: Partial<T>, 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;
Expand All @@ -74,6 +101,10 @@ export const useComplexState = <T extends Partial<T>>(initialValue: T[]) => {
(index) => !isInvalidOrNegativeIndex(index, complexState)
);

if (!filteredValidIndexes.length) {
return;
}

setComplexState((prevState) => {
return prevState.filter((_, idx) => !filteredValidIndexes.includes(idx));
});
Expand All @@ -86,6 +117,7 @@ export const useComplexState = <T extends Partial<T>>(initialValue: T[]) => {
insertMany,
update,
partialUpdate,
partialUpdateMany,
remove,
removeMany,
};
Expand Down

0 comments on commit 786692a

Please sign in to comment.