Last active
August 26, 2020 14:08
-
-
Save icylace/0c7962343bb6e0566aadf06df2958f97 to your computer and use it in GitHub Desktop.
Merges `class` property values for Hyperapp elements.
This file contains 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
// The `class` property for Hyperapp virtual DOM elements can take multiple | |
// forms. This function is able to merge two such values using the form | |
// of the initial value if possible. | |
const mergeClasses = (a, b) => { | |
if (typeof a === "boolean") { | |
return b | |
} | |
if (typeof a === "string") { | |
if (typeof b === "boolean") { | |
return a | |
} | |
if (typeof b === "string") { | |
return b ? a + " " + b : a | |
} | |
if (Array.isArray(b)) { | |
return [a, ...b].join(" ") | |
} | |
if (typeof b === "object") { | |
return Object.entries(b).reduce((xs, [k, v]) => v ? [...xs, k] : xs, [a]).join(" ") | |
} | |
} | |
if (Array.isArray(a)) { | |
if (typeof b === "boolean" || typeof b === "string") { | |
return [...a, b] | |
} | |
if (Array.isArray(b)) { | |
return [...a, ...b] | |
} | |
if (typeof b === "object") { | |
return Object.entries(b).reduce((xs, [k, v]) => v ? [...xs, k] : xs, a) | |
} | |
} | |
if (typeof a === "object") { | |
if (typeof b === "boolean") { | |
return a | |
} | |
if (typeof b === "string") { | |
return { ...a, b: true } | |
} | |
if (Array.isArray(b)) { | |
return b.reduce((r, x) => x ? { ...r, [x]: true } : r, a) | |
} | |
if (typeof b === "object") { | |
return { ...a, ...b } | |
} | |
} | |
return a | |
} |
Author
icylace
commented
Aug 26, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment