Last active
June 6, 2018 10:18
-
-
Save ChrisDobby/a0ffe61bbf176797aaf1ff388955e1b4 to your computer and use it in GitHub Desktop.
Creates a css class on the fly from an object
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 ClassName = () => { | |
const createdClasses = []; | |
const stringToCss = str => str.split('').map(c => c.charCodeAt(0) >= 97 | |
? c | |
: `-${String.fromCharCode(c.charCodeAt(0) + 32)}`).join(''); | |
const cssString = css => Object.keys(css).map(key => `${stringToCss(key)}:${css[key]}`).join(';'); | |
const addStyle = (name, css) => { | |
const style = document.createElement('style'); | |
style.appendChild(document.createTextNode(`.${name}{${cssString(css)}}`)); | |
document.head.appendChild(style); | |
}; | |
const objWithSortedProps = (obj) => { | |
const sortedObj = {}; | |
for (const key of Object.keys(obj).sort()) { | |
sortedObj[key] = obj[key]; | |
} | |
return sortedObj; | |
} | |
const getClass = getHash => (css) => { | |
const sortedCss = objWithSortedProps(css); | |
const cssHash = getHash(sortedCss); | |
const currentClass = createdClasses.find(cls => cls === cssHash); | |
if (typeof currentClass !== 'undefined') { | |
return currentClass; | |
} | |
createdClasses.push(cssHash); | |
addStyle(cssHash, sortedCss); | |
return cssHash; | |
}; | |
return { | |
getClass, | |
}; | |
} | |
export default ClassName(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment