Skip to content

Instantly share code, notes, and snippets.

@nyk0r
Created October 4, 2016 19:26
Show Gist options
  • Save nyk0r/ff9e8209e88d9c2745fe808649c25ba9 to your computer and use it in GitHub Desktop.
Save nyk0r/ff9e8209e88d9c2745fe808649c25ba9 to your computer and use it in GitHub Desktop.
function flatten<T>(arr: Array<T|Array<T>>): Array<T> {
let result: Array<T> = [];
let stack: Array<{ arr: Array<T | Array<T>>, idx: number }> =
[{ arr, idx: 0 }];
main: while (stack) {
let {arr: current, idx} = stack.pop();
for (; idx < current.length; idx++) {
if (current[idx] instanceof Array) {
stack.push({arr: current, idx});
stack.push({arr: <Array<T>>current[idx], idx: 0});
continue main;
} else {
result.push(<T>current[idx]);
}
}
}
return result;
}
console.log(flatten([1, [2, [3, 4], 5], 6, [7]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment