Skip to content

Instantly share code, notes, and snippets.

@nite
Last active January 5, 2018 09:17
Show Gist options
  • Save nite/38fe069a152b1fcd2aaa404cf86f37d0 to your computer and use it in GitHub Desktop.
Save nite/38fe069a152b1fcd2aaa404cf86f37d0 to your computer and use it in GitHub Desktop.
Serialise input as key-value pair string, eg. for human-readable logs.
/**
* Serialise input as key-value pair string, eg. for human-readable logs.
*
* @param {any} body
* @param {number} nest
* @param {string} delimiter
* @param {string} arrayDelimiter
* @param {boolean} nested
* @returns {string}
*/
toKeyValuePairString(body, nest = 2, delimiter = ' | ', arrayDelimiter = ', ', nested = false) {
return isNull(body) ? 'null'
: isUndefined(body) ? 'undefined'
: Array.isArray(body)
? '[' + body.map(item => toKeyValuePairs(item, nest, delimiter, arrayDelimiter, true))
.join(arrayDelimiter) + ']'
: typeof(body) === 'object'
? (nested ? '{' : '')
+ Object.entries(body).map(pair =>
nest > 0
? [pair[0], toKeyValuePairs(pair[1], nest - 1, delimiter, arrayDelimiter, true)].join('=')
: [pair[0], pair[1]].join('=')).join(delimiter) + (nested ? '}' : '')
: String(body);
}
it('should serialise object to kvp', () => {
const thing = {
id: 1,
name: 'fred',
sibling: null,
god: undefined,
tags: [1, 2, 3],
child: {name: 'bob'},
};
const actual = toKeyValuePairString(thing);
expect(actual).toEqual('id=1 | name=fred | sibling=null | god=undefined | tags=[1, 2, 3] | child={name=bob}');
expect(toKeyValuePairString('bob')).toEqual('bob');
expect(toKeyValuePairString([1, 2, 3])).toEqual('[1, 2, 3]');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment