Last active
March 28, 2020 18:07
-
-
Save melwyn95/2dcdcd467173b53fec9fff532093bc58 to your computer and use it in GitHub Desktop.
Array Flattening (Iterative Version)
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(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