Last active
October 15, 2018 19:19
-
-
Save jeffvan576/53c9a98d1a8b2eb91b94e4232081eda6 to your computer and use it in GitHub Desktop.
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
/* Final Refactor */ | |
// This is the final form of the function. I included the first iteration below to show my thought process as well as how the code was refactored | |
function flatten (arr) { | |
if (!Array.isArray(arr)) return -1; | |
return arr.reduce((p, c) => !Array.isArray(c) ? p.concat(c) : p.concat(flatten(c)), []); | |
} | |
/* End Final Refactor */ | |
/* First Iteration - With Comments */ | |
function flatten (arr) { | |
// Established a check to determine if the array being passed in is actually an array - if not, return -1; | |
if (!Array.isArray(arr)) return -1; | |
// Reduce over the array | |
return arr.reduce((p, c) => { | |
// At each index, test if the item is not an array. If it is not, add it to the flattened list (p) | |
if (!Array.isArray(c)) { | |
return p.concat(c); | |
} else { | |
// If the index item is an array, recurse through applying the same logic on the subset array. | |
return p.concat(flatten(c)) | |
} | |
}, []) | |
} | |
/* End First Iteration */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Jeff,
thanks for this submission, your code looks good!
Just one question: why does the
flatten
function return-1
in case the input is not an array?Thanks!
Stefano