Skip to content

Instantly share code, notes, and snippets.

@the1mills
Last active November 25, 2018 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save the1mills/61d53438a3dce1da32640d3e05a611a6 to your computer and use it in GitHub Desktop.
Save the1mills/61d53438a3dce1da32640d3e05a611a6 to your computer and use it in GitHub Desktop.
Reducing each node in tree to branches representation
'use strict';
const animals = {
canines: {
dogs: {
poodle: {
val: true
}
},
fox:{
val: true
},
wolf: {
northwestern:{
val: true
},
arctic: {
val: true
}
},
raccoon:{
val: true
}
},
porpoises: {
vaquita:{
val: true
},
harbor: {
val: true
}
},
};
const uppercaseFirstChar = s => {
return s.slice(0,1).toUpperCase() + s.slice(1).toLowerCase();
};
const loop = (v, list, cb) => {
const results = [];
async.eachLimit(Object.keys(v), 3, (k, cb) => {
const sub = v[k];
if (sub && typeof sub === 'object') {
for (let l of list) {
l.push({
key: k
});
}
return loop(sub, list.concat([results]), err => {
const path = results.reduce((a, b) => {
return {
val: a.val,
key: uppercaseFirstChar(a.key) + '.' + uppercaseFirstChar(b.key)
}
});
console.log({path});
cb(err);
});
}
for (let l of list) {
l.push({
val: sub,
key: k
});
}
process.nextTick(cb);
}, cb);
};
const list = [];
loop(animals, list, (err, val) => {
console.log(err, val);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment