Created
June 2, 2020 09:06
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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