Trying to dust off the pipes on recursion here. Can anyone give me a hand?
I have a JavaScript object of keys that contain an array of other keys in their values. Using JavaScript I am trying to normalize the list so I can see which keys belong as dependencies to the key in question. Let me explain visually:
Here is the object (itemDepsMap):
{
"zero" : '',
"one" : ['zero'],
"two" : ['one'],
"three": ['one', 'two'],
"four" : ['three']
}
So the key four depends on three, which depends on one and two, which depend on one and zero
I need a function called checkDeps(id) which will return as follows"
checkDeps('four') => [three, two, one, zero] checkDeps('two') => [one, zero]
I believe this is called a closure. I also believe that this is to be done recursively.
Here's what I have:
this.checkDeps = function(id) {
var closure = [];
if(this.itemDepsMap[id] !== ''){
for(var dep in this.itemDepsMap[id]) {
console.log(this.itemDepsMap[id][dep]);
closure = this.checkDeps(this.itemDepsMap[id][dep]);
}
}
return closure;
}
I would really appreciate some help here! Duplicates are not important, but bonus points if the solution doesn't add duplicates (elegantly..)