Created
August 23, 2015 21:14
-
-
Save py-in-the-sky/4c2dadb733052475d022 to your computer and use it in GitHub Desktop.
Lazily flatten a nested array with generator functions
This file contains hidden or 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
// 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