Skip to content

Instantly share code, notes, and snippets.

@danprince
Last active July 8, 2016 08:12
Show Gist options
  • Save danprince/b30c9cf159ce322fdef7d8f88b41952c to your computer and use it in GitHub Desktop.
Save danprince/b30c9cf159ce322fdef7d8f88b41952c to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested elements.
// 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, []);
}
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