Skip to content

Instantly share code, notes, and snippets.

@py-in-the-sky
Created August 23, 2015 21:14
Show Gist options
  • Save py-in-the-sky/4c2dadb733052475d022 to your computer and use it in GitHub Desktop.
Save py-in-the-sky/4c2dadb733052475d022 to your computer and use it in GitHub Desktop.
Lazily flatten a nested array with generator functions
// Works in Chrome devtools console.
/* Yields each non-array element from a potentially nested array. */
function* lazyFlatten (element) {
if (!Array.isArray(element))
yield element; // yield non-array element
else
for (var element2 of element) // unpack array into sub-elements
for (var element3 of lazyFlatten(element2)) // flatten each sub-element...
yield element3; // and yield its elements
}
var nestedArray = [1, 2, [3, [4, 5]], [6, 7]];
for (var nonArray of lazyFlatten(nestedArray))
console.log(nonArray);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment