Skip to content

Instantly share code, notes, and snippets.

@andrezsanchez
Last active December 30, 2016 22:35
Show Gist options
  • Save andrezsanchez/5d3b28d260050e9aa54b77599e99c1f9 to your computer and use it in GitHub Desktop.
Save andrezsanchez/5d3b28d260050e9aa54b77599e99c1f9 to your computer and use it in GitHub Desktop.
Flattens an array using a stack
function flatten(a) {
if (!Array.isArray(a)) throw new TypeError('argument must be array');
let stack = [a];
let stackIndex = [0];
let rv = [];
while (stack.length > 0) {
const i = stack.length - 1;
if (stackIndex[i] >= stack[i].length) {
stack.pop();
stackIndex.pop();
}
else {
const x = stack[i][stackIndex[i]];
if (Array.isArray(x)) {
stack.push(x);
stackIndex.push(0);
}
else {
rv.push(x);
}
stackIndex[i] += 1;
}
}
return rv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment