Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created September 13, 2023 23:23
Show Gist options
  • Save DavidWells/d31d3ce090319689530371e83232ed32 to your computer and use it in GitHub Desktop.
Save DavidWells/d31d3ce090319689530371e83232ed32 to your computer and use it in GitHub Desktop.
stringify object into one line
const props = {
text: 'hello',
boolean: true,
array: ['hi', 'there', true],
object: {
cool: true,
nice: 'awesome'
},
func: () => {},
nullish: null,
undef: undefined
}
function stringifyOptions(obj, opts = {}) {
const joiner = opts.joiner || '='
const attrs = Object.entries(obj)
// filter out non-serializable values
.filter(([attr, val]) => {
const type = typeof val
return type !== 'undefined' && val !== null && type !== 'function'
})
.map(([attr, val]) => {
const value = format(val)
/* return array of items */
if (Array.isArray(value)) {
const mapped = format(val)
return `${attr}${joiner}{[${mapped.join(', ')}]}`
}
if (typeof val === 'object') {
return `${attr}${joiner}{${stringifyWithSpaces(val)}}`
}
return `${attr}${joiner}${value}`
}).join(opts.separator || ' ');
return attrs
}
function format(val) {
const type = typeof val
console.log('type', type)
if (type === 'string') {
return ensureQuote(val)
}
if (Array.isArray(val)) {
return val.map((v) => format(v))
}
if (type === 'undefined' || val === null) return val
if (typeof val === 'object') {
return Object.entries(val).reduce((acc, [attr, v]) => {
acc[attr] = format(v)
return acc
}, {})
}
return val
}
function stringifyWithSpaces(obj) {
// stringify, with line-breaks and indents
let result = JSON.stringify(obj, null, 1)
// remove all but the first space for each line
result = result.replace(/^ +/gm, " ")
// remove line-breaks
result = result.replace(/\n/g, "")
// remove spaces between object-braces and first/last props
result = result.replace(/{ /g, "{").replace(/ }/g, "}")
// remove spaces between array-brackets and first/last items
result = result.replace(/\[ /g, "[").replace(/ \]/g, "]")
return result
}
/**
* Wrap string in characters if not already wrapped in them
* @param {string|Array<string>} value
* @param {string} open
* @param {string} close
* @returns {string|string[]}
*/
function ensureQuote(value, open, close) {
const start = open || '"'
const end = close || start
let i = -1
const result = []
if (Array.isArray(value)) {
while (++i < value.length) {
result[i] = startChar(value[i], start) + value[i] + endChar(value[i], end)
}
return result
}
return startChar(value, start) + value + endChar(value, end)
}
function startChar(str, char) {
return (str[0] === char) ? '' : char
}
function endChar(str, char) {
return (str[str.length -1] === char) ? '' : char
}
const result = stringifyOptions(props, {
// separator: '\n',
// joiner: ':'
})
console.log('result')
console.log(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment