EDIT
To me JSON.stringify
is not the solution here, as it is much slower than recursion
JSON.stringify(fakeData)
.replace(/,/g, ';')
.replace(/:(?={)/g, '')
.replace(/"/g, '')
//Result
Recursion with reduce x 816,321 ops/sec ±7.38% (80 runs sampled)
JSON.stringify x 578,221 ops/sec ±1.72% (92 runs sampled)
Fastest is Recursion with reduce
I am making a css-in-js library, and I need to use recursion to turn object into string like this:
Input:
const fakeData = {
a: {
b: 'c',
d: 'e'
}
}
Output:
a{b:c;d:e;}
My recursion function:
const buildKeyframe = (obj) => {
return Object.entries(obj).reduce((acc, (prop, value)) => {
if (typeof value === 'string') {
return `${acc}${prop}:${value};`
}
return `${acc}${prop}:{${buildKeyframe(value)}}`
}, '')
}
This function works, but I think there is room for improvement(e.g. use TCO, avoid using reduce
)… How can I write a better function to recurse this data structure?