From 3b9e3c6af0ea5b3b780266be9a722b7db042512d Mon Sep 17 00:00:00 2001 From: Tsu-ba-me Date: Thu, 2 Mar 2023 23:00:53 -0500 Subject: [PATCH] fix(striker-ui): make buildMapToMessageSetter() handle array ids --- striker-ui/lib/buildMapToMessageSetter.ts | 54 ++++++++++++++++------- striker-ui/types/MapToMessageSetter.d.ts | 16 +++++++ 2 files changed, 55 insertions(+), 15 deletions(-) create mode 100644 striker-ui/types/MapToMessageSetter.d.ts diff --git a/striker-ui/lib/buildMapToMessageSetter.ts b/striker-ui/lib/buildMapToMessageSetter.ts index fe0b5dbd..5152ab33 100644 --- a/striker-ui/lib/buildMapToMessageSetter.ts +++ b/striker-ui/lib/buildMapToMessageSetter.ts @@ -2,25 +2,49 @@ import { MutableRefObject } from 'react'; import { MessageGroupForwardedRefContent } from '../components/MessageGroup'; -type BuildMapToMessageSetterReturnType = { - [MessageSetterID in keyof T]: MessageSetterFunction; +const buildMessageSetter = ( + id: string, + messageGroupRef: MutableRefObject, + container?: MapToMessageSetter, + key: string = id, +): MessageSetterFunction => { + const setter: MessageSetterFunction = (message?) => { + messageGroupRef.current.setMessage?.call(null, id, message); + }; + + if (container) { + container[key as keyof T] = setter; + } + + return setter; }; -const buildMapToMessageSetter = ( - mapToID: T, +const buildMapToMessageSetter = < + U extends string, + I extends InputIds, + M extends MapToInputId, +>( + ids: I, messageGroupRef: MutableRefObject, -): BuildMapToMessageSetterReturnType => - Object.entries(mapToID).reduce>( - (previous, [key, id]) => { - const setter: MessageSetterFunction = (message?) => { - messageGroupRef.current.setMessage?.call(null, id, message); - }; - - previous[key as keyof T] = setter; +): MapToMessageSetter => { + let result: MapToMessageSetter = {} as MapToMessageSetter; + if (ids instanceof Array) { + result = ids.reduce>((previous, id) => { + buildMessageSetter(id, messageGroupRef, previous); return previous; - }, - {} as BuildMapToMessageSetterReturnType, - ); + }, result); + } else { + result = Object.entries(ids).reduce>( + (previous, [key, id]) => { + buildMessageSetter(id, messageGroupRef, previous, key); + return previous; + }, + result, + ); + } + + return result; +}; export default buildMapToMessageSetter; diff --git a/striker-ui/types/MapToMessageSetter.d.ts b/striker-ui/types/MapToMessageSetter.d.ts new file mode 100644 index 00000000..537f2644 --- /dev/null +++ b/striker-ui/types/MapToMessageSetter.d.ts @@ -0,0 +1,16 @@ +type MapToMessageSetter = { + [MessageSetterID in keyof T]: MessageSetterFunction; +}; + +type InputIds = ReadonlyArray | MapToInputTestID; + +/** + * Given either: + * 1. an array of input identifiers, or + * 2. a key-value object of input indentifiers, + * transform it into a key-value object of identifiers. + */ +type MapToInputId< + U extends string, + I extends InputIds, +> = I extends ReadonlyArray ? { [K in I[number]]: K } : I;