Skip to content

Instantly share code, notes, and snippets.

@icylace
Last active August 26, 2020 14:08
Show Gist options
  • Save icylace/0c7962343bb6e0566aadf06df2958f97 to your computer and use it in GitHub Desktop.
Save icylace/0c7962343bb6e0566aadf06df2958f97 to your computer and use it in GitHub Desktop.
Merges `class` property values for Hyperapp elements.
// 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
}
@icylace
Copy link
Author

icylace commented Aug 26, 2020

// Example usage:

const haze = true
const foggy = false

console.log(mergeClasses("hello", "world"))
// "hello world"

console.log(mergeClasses("hello", { mars: false, world: true }))
// "hello world"

console.log(mergeClasses(["purple", haze && "haze"], "violet"))
// ["purple", "haze", "violet"]

console.log(mergeClasses({ common: true, active: false }, ["purple", haze && "haze", foggy && "foggy"]))
// { common: true, active: false, purple: true, haze: true }

console.log(mergeClasses(["purple", haze && "haze", foggy && "foggy"], { common: true, active: false }))
// ["purple", "haze", false, "common"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment