From 499a28e4c01db4b0b0a7e9203ee7e59aa36307db Mon Sep 17 00:00:00 2001 From: Samuel Rowe Date: Fri, 29 Jul 2022 21:31:00 +0530 Subject: [PATCH] feat(frontend): created `pruneObject` and `pruneArray` utilities --- services/frontend/src/utils/forms.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/services/frontend/src/utils/forms.ts b/services/frontend/src/utils/forms.ts index 931a359..9704779 100644 --- a/services/frontend/src/utils/forms.ts +++ b/services/frontend/src/utils/forms.ts @@ -1,3 +1,5 @@ +import lodash from "lodash"; + export const checkArray = (array: any, name: string): T => { if (!Array.isArray(array)) { throw new Error( @@ -6,3 +8,19 @@ export const checkArray = (array: any, name: string): T => { } return array as unknown as T; }; + +export const pruneArray = (array: (T | undefined)[]): T[] | undefined => { + const result = array.filter(Boolean); + if (array.length === 0) { + return undefined; + } + return result as T[]; +}; + +export const pruneObject = (object: T): unknown | undefined => { + const result = lodash.pickBy(object ?? {}, (value) => value !== undefined); + if (Object.keys(result).length === 0) { + return undefined; + } + return result as unknown; +};