tc39 / proposal-flatMap

proposal for flatten and flatMap on arrays
https://tc39.github.io/proposal-flatMap
214 stars 19 forks source link

Proposal for Array.depth to get depth of an nested array. #68

Closed dhunmoon closed 6 years ago

dhunmoon commented 6 years ago

How about an inbuilt function to find the depth of an array, There is already an Experimental feature Array.prototype.flatten(depth) which accepts a depth value up to which array needed to be flatten But there is no inbuilt way to get the depth of an array. Currently to get the depth we have to do something like. which is an implicit way to get depth.

function depthOf(arr) {
    if(!Array.isArray(arr))
        throw "Not an Array"
    var depth = 1;
    var i;
    for(var i = 0; i< arr.length; i++){
        if (!Array.isArray(arr[i])) continue;

        if(Array.isArray(arr[i])){
            var depth = depthOf(arr[i]) + 1;
            depth = Math.max(depth, depth);
        }
    }
    return depth;
}

If there is option to get depth explicitely that would be great. We already have property of array like Array.length why not have another property like Array.depth.

Any thoughts.

ljharb commented 6 years ago

What would the depth be of const arr = []; arr.push([arr]); arr.depth?

dhunmoon commented 6 years ago

@ljharb for your example it should output 2.

IgnoredAmbience commented 6 years ago

The array that ljharb gives is self-referential. The given draft algorithm doesn't terminate when given such an array.

ljharb commented 6 years ago

Right - that array has an infinite depth.

dhunmoon commented 6 years ago

@IgnoredAmbience I had no idea that seld referring array can have the depth of Infinite I cannot wrap my head around it how it's happening.

It means whenever you push an array arr1 inside another array arr2 then it's just pushing the reference of that array, and after that, if I change the content of arr1 then arr2 will also change.

tabatkins commented 6 years ago

The example doesn't use an arr1 and arr2, it uses a single arr and pushes it into itself. Try it out on your own - how many arr[0][0][0][0][0][0][0]... things can you do before you hit undefined?