Last active
April 21, 2017 15:21
-
-
Save mattpodwysocki/b92054435d3e51cea4bb166f1c9f5233 to your computer and use it in GitHub Desktop.
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<T>(iterable: Iterable<T>, depth: number = Infinity): Iterable<T> { | |
if (depth === 0) { return iterable; } | |
for (let item of iterable) { | |
if (typeof item[Symbol.iterator] === 'function') { | |
yield *flatten(item, depth - 1); | |
} else { | |
yield item; | |
} | |
} | |
} | |
const arr = [1,[2],[3,4]]; | |
const result = flatten(arr); | |
for (let item of result) { | |
console.log(result); | |
} |
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 *flattenAsync<T>(iterable: AsyncIterable<T>, depth: number = Infinity): AsyncIterable<T> { | |
if (depth === 0) { return iterable; } | |
for await (let item of iterable) { | |
if (typeof item[Symbol.asyncIterator] === 'function') { | |
yield *flatten(item, depth - 1); | |
} else { | |
yield item; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment