All files / src/bin-utils/initialize stringify-object.js

100% Statements 10/10
100% Branches 4/4
100% Functions 5/5
100% Lines 10/10
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                      11x 26x   26x 6x   20x   26x 26x         26x       26x       20x        
import {isPlainObject} from 'lodash'
 
/**
 * Converts given object to its string representation.
 * Every line is preceded by given indent.
 *
 * @param {object} object "Object to convert"
 * @param {string} indent "Indent to use"
 * @returns {string} "Stringified and indented object"
 */
function stringifyObject(object, indent) {
  return Object.keys(object).reduce((string, key, index) => {
    const script = object[key]
    let value
    if (isPlainObject(script)) {
      value = `{${stringifyObject(script, `${indent}  `)}\n${indent}}`
    } else {
      value = `'${escapeSingleQuote(script)}'`
    }
    const comma = getComma(isLast(object, index))
    return `${string}\n${indent}${key}: ${value}${comma}`
  }, '')
}
 
function getComma(condition) {
  return condition ? '' : ','
}
 
function isLast(object, index) {
  return Object.keys(object).length - 1 === index
}
 
function escapeSingleQuote(string) {
  return string.replace(/'/g, "\\'")
}
 
export default stringifyObject