From fa2f68574ecc61a49f9c56696389f2248a052c39 Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Fri, 31 Mar 2023 22:35:37 -0400 Subject: [PATCH] fix(striker-ui): add regexp object state setter callback --- .../lib/buildObjectStateSetterCallback.ts | 44 +++++++++++++++---- .../types/BuildObjectStateSetterCallback.d.ts | 1 + 2 files changed, 37 insertions(+), 8 deletions(-) diff --git a/striker-ui/lib/buildObjectStateSetterCallback.ts b/striker-ui/lib/buildObjectStateSetterCallback.ts index 85aca14f..40547c6d 100644 --- a/striker-ui/lib/buildObjectStateSetterCallback.ts +++ b/striker-ui/lib/buildObjectStateSetterCallback.ts @@ -8,25 +8,29 @@ const checkUnset = ( { isOverwrite = false }: { isOverwrite?: boolean } = {}, ): boolean => !(key in obj) || isOverwrite; +const defaultObjectStatePropSetter = ( + ...[, result, key, value]: Parameters> +): ReturnType> => { + if (value !== undefined) { + result[key] = value; + } +}; + const buildObjectStateSetterCallback = ( key: keyof S, value?: S[keyof S], { - guard, - set = (o, k, v) => { - if (v !== undefined) { - o[k] = v; - } - }, + guard = () => true, + set = defaultObjectStatePropSetter, }: BuildObjectStateSetterCallbackOptions = {}, ): BuildObjectStateSetterCallbackReturnType => (previous: S): S => { const { [key]: toReplace, ...restPrevious } = previous; const result = { ...restPrevious } as S; - if (guard?.call(null, previous, key, value)) { - set(result, key, value); + if (guard(previous, key, value)) { + set(previous, result, key, value); } return result; @@ -43,4 +47,28 @@ export const buildProtectedObjectStateSetterCallback = ( ): BuildObjectStateSetterCallbackReturnType => buildObjectStateSetterCallback(key, value, { isOverwrite, guard, set }); +export const buildRegExpObjectStateSetterCallback = + ( + re: RegExp, + value?: S[keyof S], + { + set = defaultObjectStatePropSetter, + }: Pick, 'set'> = {}, + ) => + (previous: S): S => { + const result: S = {} as S; + + Object.keys(previous).forEach((key) => { + const k = key as keyof S; + + if (re.test(key)) { + set(previous, result, k, value); + } else { + result[k] = previous[k]; + } + }); + + return result; + }; + export default buildObjectStateSetterCallback; diff --git a/striker-ui/types/BuildObjectStateSetterCallback.d.ts b/striker-ui/types/BuildObjectStateSetterCallback.d.ts index dd2aa60f..bdd142bc 100644 --- a/striker-ui/types/BuildObjectStateSetterCallback.d.ts +++ b/striker-ui/types/BuildObjectStateSetterCallback.d.ts @@ -7,6 +7,7 @@ type ObjectStatePropGuard = ( ) => boolean; type ObjectStatePropSetter = ( + previous: S, result: S, key: keyof S, value?: S[keyof S],