Skip to content

Instantly share code, notes, and snippets.

@akumbhani66
Last active August 2, 2017 06:07
Show Gist options
  • Save akumbhani66/204f9dea04e253147bbfd37a6ad01b41 to your computer and use it in GitHub Desktop.
Save akumbhani66/204f9dea04e253147bbfd37a6ad01b41 to your computer and use it in GitHub Desktop.
deep counting.
Array.length will give you the number of top-level elements in an array.
Your task is to create a function deepCount that returns the number of ALL elements within an array, including any within inner-level arrays.
For example:
deepCount([1, 2, 3]);
//>>>>> 3
deepCount(["x", "y", ["z"]]);
//>>>>> 4
deepCount([1, 2, [3, 4, [5]]]);
//>>>>> 7
The input will always be an array.
=============================solution============================================================
function deepCount(a){
return (Array.from(flatten(a)).length) + depthOf(a);
}
function depthOf(object) {
var level = 0;
var key;
for(key in object) {
if (!object.hasOwnProperty(key)) continue;
if(typeof object[key] == 'object'){
var depth = depthOf(object[key]) + 1;
level = Math.max(depth, level);
}
}
return level;
}
function *flatten(array) {
for (elt of array)
if (Array.isArray(elt)) yield *flatten(elt);
else yield elt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment