fix(striker-ui): add regexp object state setter callback

main
Tsu-ba-me 2 years ago
parent 23ea09ed35
commit fa2f68574e
  1. 44
      striker-ui/lib/buildObjectStateSetterCallback.ts
  2. 1
      striker-ui/types/BuildObjectStateSetterCallback.d.ts

@ -8,25 +8,29 @@ const checkUnset = <S extends BaseObject>(
{ isOverwrite = false }: { isOverwrite?: boolean } = {}, { isOverwrite = false }: { isOverwrite?: boolean } = {},
): boolean => !(key in obj) || isOverwrite; ): boolean => !(key in obj) || isOverwrite;
const defaultObjectStatePropSetter = <S extends BaseObject>(
...[, result, key, value]: Parameters<ObjectStatePropSetter<S>>
): ReturnType<ObjectStatePropSetter<S>> => {
if (value !== undefined) {
result[key] = value;
}
};
const buildObjectStateSetterCallback = const buildObjectStateSetterCallback =
<S extends BaseObject>( <S extends BaseObject>(
key: keyof S, key: keyof S,
value?: S[keyof S], value?: S[keyof S],
{ {
guard, guard = () => true,
set = (o, k, v) => { set = defaultObjectStatePropSetter,
if (v !== undefined) {
o[k] = v;
}
},
}: BuildObjectStateSetterCallbackOptions<S> = {}, }: BuildObjectStateSetterCallbackOptions<S> = {},
): BuildObjectStateSetterCallbackReturnType<S> => ): BuildObjectStateSetterCallbackReturnType<S> =>
(previous: S): S => { (previous: S): S => {
const { [key]: toReplace, ...restPrevious } = previous; const { [key]: toReplace, ...restPrevious } = previous;
const result = { ...restPrevious } as S; const result = { ...restPrevious } as S;
if (guard?.call(null, previous, key, value)) { if (guard(previous, key, value)) {
set(result, key, value); set(previous, result, key, value);
} }
return result; return result;
@ -43,4 +47,28 @@ export const buildProtectedObjectStateSetterCallback = <S extends BaseObject>(
): BuildObjectStateSetterCallbackReturnType<S> => ): BuildObjectStateSetterCallbackReturnType<S> =>
buildObjectStateSetterCallback(key, value, { isOverwrite, guard, set }); buildObjectStateSetterCallback(key, value, { isOverwrite, guard, set });
export const buildRegExpObjectStateSetterCallback =
<S extends BaseObject>(
re: RegExp,
value?: S[keyof S],
{
set = defaultObjectStatePropSetter,
}: Pick<BuildObjectStateSetterCallbackOptions<S>, '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; export default buildObjectStateSetterCallback;

@ -7,6 +7,7 @@ type ObjectStatePropGuard<S extends BaseObject> = (
) => boolean; ) => boolean;
type ObjectStatePropSetter<S extends BaseObject> = ( type ObjectStatePropSetter<S extends BaseObject> = (
previous: S,
result: S, result: S,
key: keyof S, key: keyof S,
value?: S[keyof S], value?: S[keyof S],

Loading…
Cancel
Save