Created
June 2, 2023 17:58
-
-
Save vorant94/6217008392270516b15d62cd3e3928fd 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
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