Skip to content

Instantly share code, notes, and snippets.

@melwyn95
Last active March 28, 2020 18:07
Show Gist options
  • Save melwyn95/2dcdcd467173b53fec9fff532093bc58 to your computer and use it in GitHub Desktop.
Save melwyn95/2dcdcd467173b53fec9fff532093bc58 to your computer and use it in GitHub Desktop.
Array Flattening (Iterative Version)
function flatten(xs) {
var ys = [];
var stack = [[0, xs]];
while(stack.length > 0) {
var [index, arr] = stack.pop();
while(index < arr.length) {
if (Array.isArray(arr[index])) {
stack.push([index+1, arr]);
stack.push([0, arr[index]]);
break;
} else {
ys.push(arr[index]);
}
index++;
}
}
return ys;
}
flatten([1, [2, [3, [4, [5, [6, [7, [8, [9, [10]]]]]]]]]])
flatten([1, [2, [3, [4, [5, [6, [7, [8, [9, [10], 11], 12], 13], 14], 15], 16], 17], 18], 19])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment