Last active
January 28, 2020 07:01
-
-
Save deanacus/7279631405b5a252ac4ecba10ed31bed to your computer and use it in GitHub Desktop.
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
/** | |
* themeGetObject | |
* | |
* Generates an object with a 'get' property for each property on a theme object. | |
* Each property is a function that returns a value from that theme property. | |
* | |
* @param theme The theme to return an object for | |
* | |
* @returns {Function} | |
* | |
* @example Simple Usaage | |
* | |
* const get = themeGetObject(themeObject); | |
* | |
* get.getColor('primary', 5); // this returns the 5th index of the sub-proprty "primary" on the colors property | |
*/ | |
const themeGetObject = ( theme = {} ) => { | |
const getValue = (key) => { | |
if(Array.isArray(theme[key]) || Object.prototype.toString.call(theme[key]) === '[object Object]') { | |
return (prop, ind = 5) => (!Array.isArray(theme[key][prop])) ? theme[key][prop] : theme[key][prop][ind]; | |
} | |
return () => theme[key] | |
} | |
const buildFunctionName = name => { | |
const shortName = name[0].toUpperCase() + (name.endsWith("s") ? name.slice(1, -1) : name.slice(1)); | |
const prefix = "get"; | |
return `${prefix}${shortName}`; | |
}; | |
return Object.keys(theme).reduce((accumulator, currentKey) => { | |
const funcName = buildFunctionName(currentKey) | |
accumulator[funcName] = getValue(currentKey); | |
return accumulator | |
}, {}); | |
} | |
/** | |
* themeGetFunction | |
* | |
* A function that returns a function. It generates an object with a property | |
* for each value on the theme that is a function to return a value from that | |
* theme value | |
* | |
* @param theme The theme to return a function for | |
* | |
* @returns {Function} | |
* | |
* @example Simple usage | |
* | |
* const get = themeGetFunction(themeObject); | |
* | |
* get('colors' 'primary' '5' ); // this returns the 5th index of the sub-proprty "primary" on the colors property | |
* | |
*/ | |
const themeGetFunction = ( theme = {} ) => { | |
const getValue = (key) => { | |
if(Array.isArray(theme[key]) || Object.prototype.toString.call(theme[key]) === '[object Object]') { | |
return (prop, ind = 5) => (!Array.isArray(theme[key][prop])) ? theme[key][prop] : theme[key][prop][ind]; | |
} | |
return () => theme[key] | |
} | |
const getters = Object.keys(theme).reduce((accumulator, currentKey) => { | |
accumulator[currentKey] = getValue(currentKey); | |
return accumulator | |
}, {}); | |
return (key, prop, index) => { | |
return getters[key](prop, index) | |
} | |
} | |
const getObject = themeGetObject(theme); | |
const getFunction = themeGetFunction(theme); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment