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],