Skip to content

Instantly share code, notes, and snippets.

@dmail
Created June 2, 2020 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmail/81995198fc1bb2869c1eb1ccc7337a63 to your computer and use it in GitHub Desktop.
Save dmail/81995198fc1bb2869c1eb1ccc7337a63 to your computer and use it in GitHub Desktop.
make props overridable by composition. In the end might be better to make this explicit otherwise it becomes hard to follow.
const composeProps = (leftProps, rightProps) => {
const composedProps = { ...rightProps }
Object.keys(leftProps).forEach((key) => {
const leftValue = leftProps[key]
if (key in rightProps) {
const rightValue = rightProps[key]
composedProps[key] = composeProp(leftValue, rightValue)
} else {
composedProps[key] = leftValue
}
})
return composedProps
}
const composeProp = (leftValue, rightValue) => {
if (typeof leftValue === "function") {
if (typeof rightValue === "function") {
return (...args) => {
leftValue(...args)
rightValue(...args)
}
}
return leftValue
}
if (typeof leftValue === "object") {
if (typeof rightValue === "object") {
return { ...leftValue, ...rightValue }
}
return leftValue
}
return rightValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment