Created
April 8, 2017 20:16
-
-
Save slacktracer/13f90ee415ea16fac3700f8c44a9f9f4 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
const flatten = function flatten(array) { | |
const flattened = array.reduce( | |
function reducer(reduced, arrayItem) { | |
const arrayItemIsArray = Array.isArray(arrayItem); | |
if (arrayItemIsArray) return reduced.concat(flatten(arrayItem)); | |
return reduced.concat(arrayItem); | |
}, | |
[] | |
); | |
return flattened; | |
} | |
const test = function test() { | |
const x = [[1,2,[3]],4]; | |
const expected = '1,2,3,4'; | |
const flattened = flatten(x); | |
if (flattened.toString() === expected) { | |
console.log('OK!'); | |
} else { | |
console.error(`FAIL! Expected ${expected}. Got ${flattened.toString()}.`); | |
} | |
return flatten(x); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On Node:
.load flatten.js
Then:
test();
Then:
PROFIT!