Skip to content

Commit

Permalink
Merge pull request #2236 from adevinta/feat-add-create-split-props
Browse files Browse the repository at this point in the history
feat(internal-utils): add new createSplitProps util
  • Loading branch information
acd02 authored Jun 15, 2024
2 parents 70cbe17 + 7e6827a commit 8262034
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/utils/internal-utils/src/create-split-props/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
type EnsureKeys<
ExpectedKeys extends (keyof Target)[],
Target,
> = keyof Target extends ExpectedKeys[number]
? unknown
: `Missing required keys: ${Exclude<keyof Target, ExpectedKeys[number]> & string}`

export const createSplitProps =
<Target>() =>
<Keys extends (keyof Target)[], Props extends Target = Target>(
props: Props,
keys: Keys & EnsureKeys<Keys, Target>
) =>
(keys as string[]).reduce<[Target, Omit<Props, Extract<(typeof keys)[number], string>>]>(
(previousValue, currentValue) => {
const [target, source] = previousValue
const key = currentValue as keyof Target & keyof typeof source
if (source[key] !== undefined) {
target[key] = source[key]
}
delete source[key]

return [target, source]
},
[{} as Target, { ...props }]
)
1 change: 1 addition & 0 deletions packages/utils/internal-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { makeVariants } from './variants'
export * as VariantTypes from './variants/types'
export * as variantConstants from './variants/constants'
export { deepFind } from './react-children-utilities/deepFind'
export { createSplitProps } from './create-split-props'

0 comments on commit 8262034

Please sign in to comment.