Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Last active December 12, 2019 16:17
Show Gist options
  • Select an option

  • Save jtmthf/ae1d6680727e27c8468f473521246b63 to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/ae1d6680727e27c8468f473521246b63 to your computer and use it in GitHub Desktop.
function* chunk<T>(
source: Iterable<T>,
size = 1,
): Iterable<IterableIterator<T>> {
const iterator = source[Symbol.iterator]();
let done = false;
function* take() {
let count = 0;
while (count++ < size) {
const result = iterator.next();
if (result.done) {
done = true;
} else {
yield result.value;
}
}
}
while (!done) {
const takeIterator = take();
const first = takeIterator.next();
if (!first.done) {
const buffer: T[] = [];
const chunkIterator = (function*() {
if (buffer.length) {
yield* buffer;
} else {
yield first.value;
yield* takeIterator;
}
})();
yield {
next: chunkIterator.next,
[Symbol.iterator]() {
return chunkIterator;
},
};
buffer.push(first.value, ...takeIterator);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment