Skip to content

Instantly share code, notes, and snippets.

@ChrisDobby
Last active June 6, 2018 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisDobby/a0ffe61bbf176797aaf1ff388955e1b4 to your computer and use it in GitHub Desktop.
Save ChrisDobby/a0ffe61bbf176797aaf1ff388955e1b4 to your computer and use it in GitHub Desktop.
Creates a css class on the fly from an object
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