Created
March 6, 2019 07:47
-
-
Save richardvanbergen/0087e9e1a31408c2af9acab494516659 to your computer and use it in GitHub Desktop.
Flattens an array of integers, throws if invalid input.
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
// DEMO: https://observablehq.com/@richardvanbergen/flattening-arrays-of-things | |
function flatten(arr) { | |
let flatArr = [] | |
for (let num of arr) { | |
if (!Array.isArray(num) && !Number.isInteger(num)) { | |
throw new Error(`Input '${num}' is not an integer!`) | |
} | |
if (Array.isArray(num)) { | |
flatArr = [...flatArr, ...flatten(num)] | |
} else { | |
flatArr.push(num) | |
} | |
} | |
return flatArr | |
} | |
flatten([1,[2],[3,[4,5]],6]) // [1, 2, 3, 4, 5, 6] | |
flatten([1, 2]) // [1, 2] | |
flatten([6,[5,[4],3],[2],1]) // [6, 5, 4, 3, 2, 1] | |
flatten([6.1]) // throws | |
flatten([{},['string',[],3],[NaN],-Infinity]) // throws |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment