Created
March 14, 2019 15:56
-
-
Save back2dev2017/e556c6f7fea7707939cac1021746a827 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Why would we do this? Well, JSON structure and NoSQL concepts come into play here: | |
// aka a document having a collection of authors, collection of editions, collection | |
// of chapters, each of those "sub arrays" having other subarrays and so on | |
// the following is javascript syntax - although I believe JS now has its own .flatten() | |
// method - I decided to code this out with recursion. It may be interesting to code this | |
// up in python and java as well to see how the code base compares | |
// for now, going to limit this to expect an array passed | |
function myFlatten(inArr) { | |
if (! Array.isArray(inArr)) throw new Error('myFlatten() called with non-array'); | |
// put array scope out here so its availble across recursive calls | |
let flatResult = []; | |
// note: if recursion depth is a concern, could make maxDepth, checkDepth variables | |
// to limit levels. Then mod the function below to increment/decrement the | |
// checkDepth - checking against maxDepth to short-ciruit another recursive call | |
function flattenArray(inArr) { | |
for (let item of inArr) { | |
if (Array.isArray(item)) { | |
flattenArray(item); | |
} else { | |
flatResult.push(item); | |
} | |
} | |
} | |
flattenArray(inArr); | |
return flatResult; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment