I\'m trying to write a function that will loop through my object and return the level depth of the object.
For example, if I ran the function on this object:
WARNING..!
Just for fun..!
Here is a solution utilizing the Y combinator phenomenon. We will uritilize an anonymous function recursively to solve the problem.
The anonymous function is as follows;
d => (o, n = 0) => o.children ? o.children.reduce(function(r,e){
var z = d(e,n+1);
return n > z ? n : z;
}, n)
: n;
There is a magical (and also non existent) function d which finds the depth of an object. If we feed our anonymous function with d it will return us a function with which we can feed an object and find it's depth.
So lets do it; :))
var Y = f => (g => g(g))(g => (o,z) => f(g(g))(o,z)),
fd = Y(d => (o, n = 0) => o.children ? o.children.reduce(function(r,e){
var z = d(e,n+1);
return n > z ? n : z;
}, n)
: n),
o = { name: 'item 1', children: [{ name: 'level 1 item', children: [{ name: 'level 2 item' }, { name: 'second level 2 item', children: [{ name: 'level 3 item' }] }] }] },
r = fd(o);
console.log(r);
If you want to find more about the Y combinator you may read this.