Last active
December 30, 2016 22:35
-
-
Save andrezsanchez/5d3b28d260050e9aa54b77599e99c1f9 to your computer and use it in GitHub Desktop.
Flattens an array using a stack
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
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