Skip to content

Instantly share code, notes, and snippets.

@KargJonas
Last active January 26, 2019 09:14
Show Gist options
  • Select an option

  • Save KargJonas/579a850a7c64fa4d1451ea9297cdafe6 to your computer and use it in GitHub Desktop.

Select an option

Save KargJonas/579a850a7c64fa4d1451ea9297cdafe6 to your computer and use it in GitHub Desktop.
// This script transforms hex numbers in objects to hex-strings (for more elegant style-code)
// The number-to-hex-string conversion
const hex = num => `#${ num.toString(16) }`
// Entries in objects that should be transformed
const TRANSFORM_ENTRIES = [
"backgroundColor",
"color"
];
// Maps through an object and transforms numbers to hex-strings
function transformStyleObj(obj) {
const res = {}
Object.entries(obj)
.map(entry => {
if (!isNaN(entry[1]) && TRANSFORM_ENTRIES.includes(entry[0]))
entry[1] = hex(entry[1])
res[entry[0]] = entry[1]
})
return res
}
const style = { backgroundColor: 0x222, color: 0xfff }
transformStyleObj(style) // => { backgroundColor: "#222", color: "#fff" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment