Last active
August 2, 2017 06:07
-
-
Save akumbhani66/204f9dea04e253147bbfd37a6ad01b41 to your computer and use it in GitHub Desktop.
deep counting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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