Skip to content

Instantly share code, notes, and snippets.

@odiak
Created October 23, 2015 08:00
Show Gist options
  • Select an option

  • Save odiak/eb268c611a1a920bc1cc to your computer and use it in GitHub Desktop.

Select an option

Save odiak/eb268c611a1a920bc1cc to your computer and use it in GitHub Desktop.
function flatten (array) {
var newArray = [];
var locals = {
i: 0,
len: array.length,
array: array,
};
var stack = [];
var elem;
while (locals) {
if (locals.i >= locals.len) {
locals = stack.pop();
continue;
}
elem = locals.array[locals.i];
locals.i += 1;
if (Array.isArray(elem)) {
stack.push(locals = {
i: 0,
len: elem.length,
array: elem,
});
} else {
newArray.push(elem);
}
}
return newArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment