Last active
September 6, 2019 03:03
-
-
Save nicksheffield/a920bb7849747a3b057009b63024d4c4 to your computer and use it in GitHub Desktop.
A function to flatten a combination of strings arrays and objects down into a single string. Used for handling conditional class names in react
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
| export const styles = (arg) => { | |
| if (typeof arg === 'string') return arg | |
| if (arg instanceof Array) { | |
| return arg | |
| .reduce((acc, arg) => { | |
| return [...acc, styles(arg)] | |
| }, []) | |
| .map((x) => x.trim()) | |
| .filter((x) => x) | |
| .join(' ') | |
| } | |
| if (typeof arg === 'object') { | |
| return Object.entries(arg) | |
| .reduce((acc, [key, val]) => { | |
| if (!val) return acc | |
| return [...acc, key] | |
| }, []) | |
| .filter((x) => x) | |
| .map((x) => x.trim()) | |
| .join(' ') | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment