Skip to content

Instantly share code, notes, and snippets.

@vorant94
Created June 2, 2023 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vorant94/6217008392270516b15d62cd3e3928fd to your computer and use it in GitHub Desktop.
Save vorant94/6217008392270516b15d62cd3e3928fd to your computer and use it in GitHub Desktop.
export class Batches<T> implements Iterable<T[]> {
constructor(private values: T[], private size: number) {
}
[Symbol.iterator](): Iterator<T[]> {
return new BatchesIterator(this.values, this.size);
}
}
class BatchesIterator<T> implements Iterator<T[]> {
private done = false;
private index = 0;
constructor(private values: T[], private size: number) {
}
next(): IteratorResult<T[], number | undefined> {
if (this.done) {
return {
done: this.done,
value: undefined
}
}
if (this.index >= this.values.length) {
this.done = true;
return {
done: this.done,
value: this.index
}
}
const value = this.values.slice(this.index, this.index + this.size);
this.index += this.size;
return {
done: false,
value
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment