Created
February 3, 2020 20:48
-
-
Save christ776/0698b43fc509d77eefcd07660604fe01 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
function flattenArray(arr) { | |
if (arr === undefined || arr === null) { | |
throw new Error('Bad argument type:', arr); | |
} | |
const flattenedArray = [].concat(...arr) | |
for(const m of flattenedArray) { | |
if (m instanceof Array) { | |
return flattenArray(flattenedArray); | |
} | |
} | |
return flattenedArray; | |
} | |
// === Some test cases ===== | |
// Complex case 1 | |
console.log(flattenArray([[1,2,[3]],4])); | |
// Complex case 2 | |
console.log(flattenArray([[1,2,[3]],4, [[[5]]]])); | |
// The empty array | |
console.log(flattenArray([])); | |
// Passing undefined as arg | |
console.log(flattenArray(undefined)); | |
//Passing null | |
console.log(flattenArray(null)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment