Last active
July 8, 2016 08:12
-
-
Save danprince/b30c9cf159ce322fdef7d8f88b41952c to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested elements.
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
// Flattens an array of arbitrarily nested elements. | |
// E.g. [[1,2,[3]],4] -> [1,2,3,4] | |
// | |
// - Doesn't work with negative array indices! | |
// - ES6 TCO requires recursion to stay in tail-call position. | |
function flatten(xs) {2 | |
if(!Array.isArray(xs)) { | |
return xs; | |
} | |
function flatConcat(xs, x) { | |
return xs.concat(flatten(x)); | |
} | |
return xs.reduce(flatConcat, []); | |
} |
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 assert = require('assert'); | |
assert.deepEqual( | |
flatten([1,2,3,4]), | |
[1,2,3,4] | |
); | |
assert.deepEqual( | |
flatten([[1,2,[3]],4]), | |
[1,2,3,4] | |
); | |
assert.deepEqual( | |
flatten([[[[1]]]]), | |
[1] | |
); | |
assert.equal( | |
flatten(1), | |
1 | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment