I've got this recursive generator function. It will traverse an object looking for "leafs", any keys that don't point to sub-objects.
Then it applies one of two actions on the leaf and yields it. Any suggestions for improvement would be appreciated. :)
const obj = {
a: 'a',
b: 'b',
c: {
d: 'd',
e: 'e',
}
};
const clone = toClone => JSON.parse(JSON.stringify(toClone))
function* leafIterator(object, action) {
for (const key of Object.keys(object)) {
if (typeof object[key] === 'object') {
for (const inner of leafIterator(object[key], action)) {
let oclone = clone(object);
oclone[key] = inner;
yield oclone;
}
}
else {
let oclone = clone(object);
action(oclone, key);
yield oclone;
}
}
}
for (let o of leafIterator(obj, (s, key) => delete s[key])) {
console.log('result', o);
}
for (let o of leafIterator(obj, (oclone, key) => {delete oclone[key];}))
and use them instead of yourif
:action(oclone, key)
. \$\endgroup\$