From f0c467ab630f2fda383f58c28c28a1e82c9e17b1 Mon Sep 17 00:00:00 2001 From: Sujan Tamang Date: Sat, 1 Oct 2022 22:08:57 +0545 Subject: [PATCH] feat(lib): add count, find & findOne new state functions --- src/index.tsx | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/index.tsx b/src/index.tsx index a5d389b..84932ea 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -8,6 +8,37 @@ import isInvalidOrNegativeIndex from "./utils/validateIndex"; export const useComplexState = >(initialValue: T[]) => { const [complexState, setComplexState] = useState(initialValue); + const getFilteredData = (filter?: Partial): T[] => { + if (!filter) { + return complexState; + } else if (typeof filter !== "object") { + return complexState.filter((item) => item === filter); + } else { + return complexState.filter((stateItem) => { + const filterKeys = Object.keys(filter); + const filterValues = Object.values(filter); + + const resultFilter = filterKeys.map( + (_, index) => + `${stateItem[filterKeys[index]]}` === `${filterValues[index]}` + ); + return Function("return " + resultFilter.join(" && "))(); + }); + } + }; + + const count = (filter?: Partial): number => { + return getFilteredData(filter).length; + }; + + const find = (filter?: Partial): T[] => { + return getFilteredData(filter); + }; + + const findOne = (filter: Partial): T | null => { + return getFilteredData(filter)[0] || null; + }; + const insert = (data: T | T[], index: number = -1) => { if (isInvalidOrNegativeIndex(index, complexState)) { if (Array.isArray(data)) { @@ -113,6 +144,9 @@ export const useComplexState = >(initialValue: T[]) => { return { value: complexState, setValue: setComplexState, + count, + find, + findOne, insert, insertMany, update,