all files / lib/utils/ build-declarations.js

100% Statements 9/9
100% Branches 2/2
100% Functions 5/5
100% Lines 8/8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                          20×                       22×                                 16×     14×    
import kebabCase from 'kebab-case'
 
/**
 * Check if the given argument is an array.
 * @param {*} arr - argument to be checked if it is an Array.
 * @returns {boolean} true if the arr is an Array.
 * @example
 * // returns true
 * isArray([])
 * @example
 * // returns false
 * isArray({})
 */
export const isArray = arr =>
  Object.prototype.toString.call(arr) === '[object Array]'
 
/**
 * Build a single css declaration.
 * @param {string} property - The property of the css declaration.
 * @param {string} value - The value of the css declaration.
 * @returns {string} formated css declaration.
 * @example
 * // returns 'width:100%;'
 * buildSingleDeclaration('width', '100%')
 */
export const buildSingleDeclaration =
  (property, value) => `${kebabCase(property)}:${value};`
 
/**
 * Build the css declarations.
 * @param {Object} declarationsObj - A style object.
 * @returns {string} formated css declarations.
 * @example
 * // returns 'border-radius-2px;'
 * buildDeclarations({borderRadius: '2px'})
 * @example
 * // returns '-webkit-user-select:none;'
 * buildDeclarations({WebkitUserSelect: 'none'})
 * @example
 * // returns 'display:-webkit-flex;display:flex;'
 * buildDeclarations({display: ['-webkit-flex', 'flex']})
 */
export default declarationsObj =>
  Object.keys(declarationsObj).reduce((previousValue, currentValue) => {
    if (isArray(declarationsObj[currentValue])) {
      return previousValue + declarationsObj[currentValue].reduce((a, b) =>
        a + buildSingleDeclaration(currentValue, b)
      , '')
    }
    return previousValue + buildSingleDeclaration(currentValue, declarationsObj[currentValue])
  }, '')