Skip to content

Instantly share code, notes, and snippets.

@mattpodwysocki
Last active April 21, 2017 15:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattpodwysocki/b92054435d3e51cea4bb166f1c9f5233 to your computer and use it in GitHub Desktop.
Save mattpodwysocki/b92054435d3e51cea4bb166f1c9f5233 to your computer and use it in GitHub Desktop.
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);
}
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