Skip to content

Instantly share code, notes, and snippets.

@hapticdata
Created September 16, 2016 18:16
Show Gist options
  • Save hapticdata/08c9d7f9e18e2ab72e715264c251f46e to your computer and use it in GitHub Desktop.
Save hapticdata/08c9d7f9e18e2ab72e715264c251f46e to your computer and use it in GitHub Desktop.
calculate the depths of nested arrays
/**
* 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
@avgspacelover
Copy link

Thanks for this!

@nick-jonas
Copy link

saved my life

@dmotz
Copy link

dmotz commented Jul 18, 2022

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