Created
September 16, 2016 18:16
-
-
Save hapticdata/08c9d7f9e18e2ab72e715264c251f46e to your computer and use it in GitHub Desktop.
calculate the depths of nested arrays
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
/** | |
* Operations to calculate the depths of a nested array | |
* @author Kyle Phillips | |
* @module 'array-depth' | |
*/ | |
const maxDepth = (a)=>{ | |
let maxVal = Number.MIN_VALUE | |
let item | |
a.forEach(val=>{ | |
let depth = max(val) | |
if(depth > maxVal){ | |
maxVal = depth | |
item = val | |
} | |
}) | |
return item | |
} | |
const minDepth = (a)=>{ | |
let minVal = Number.MAX_VALUE | |
let item | |
a.forEach(val=>{ | |
let depth = min(val) | |
if(depth < minVal){ | |
minVal = depth | |
item = val | |
} | |
}) | |
return item | |
} | |
/** | |
* find the maximum depth of nested arrays | |
* @param {Array} a | |
* @param {Number}[count] | |
*/ | |
export const max = (a, count=0)=> | |
Array.isArray(a) ? max(maxDepth(a), count + 1) : count | |
/** | |
* find the minimum depth of nested arrays | |
* @param {Array} a | |
* @param {Number} [count] | |
*/ | |
export const min = (a, count=0)=> | |
Array.isArray(a) ? min(minDepth(a), count + 1) : count | |
saved my life
This code is like a symphony. I will revisit it whenever I feel the need to be inspired.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this!