diff options
author | Sam Wilkins <samwilkins333@gmail.com> | 2019-09-13 20:17:19 -0400 |
---|---|---|
committer | Sam Wilkins <samwilkins333@gmail.com> | 2019-09-13 20:17:19 -0400 |
commit | dcbbfe6d34e89df49069a0ede64df0dc5adc6056 (patch) | |
tree | 40749b628d99c7ce7c9e23b00514d5c487e2444f /src/client/util/UtilExtensions.ts | |
parent | 3c2b04f16ccfae103e2f3acdd852e337c5f974e1 (diff) |
fixed batching and refactor
Diffstat (limited to 'src/client/util/UtilExtensions.ts')
-rw-r--r-- | src/client/util/UtilExtensions.ts | 62 |
1 files changed, 32 insertions, 30 deletions
diff --git a/src/client/util/UtilExtensions.ts b/src/client/util/UtilExtensions.ts index 1e277b242..0bf9f4e97 100644 --- a/src/client/util/UtilExtensions.ts +++ b/src/client/util/UtilExtensions.ts @@ -1,39 +1,41 @@ -module.exports.Batch = async function <T>(parameters: BatchParameters<T>) { - const { size, action } = parameters; +module.exports.Batch = function <T>(batchSize: number): T[][] { const batches: T[][] = []; let i = 0; while (i < this.length) { - const cap = Math.min(i + size, this.length); + const cap = Math.min(i + batchSize, this.length); batches.push(this.slice(i, cap)); i = cap; } - console.log(`Beginning action on ${this.length} elements, split into ${batches.length} groups => ${batches.map(batch => batch.length).join(", ")}`); - if (action) { - const { handler, interval } = action; - if (!interval || batches.length === 1) { - for (let batch of batches) { - await handler(batch); - } - } else { - return new Promise<T[][]>(resolve => { - const iterator = batches[Symbol.iterator](); - const quota = batches.length; - let completed = 0; - const tag = setInterval(async () => { - const next = iterator.next(); - if (next.done) { - clearInterval(tag); - return; - } - const batch = next.value; - console.log(`Handling next batch with ${batch.length} elements`); - await handler(batch); - if (++completed === quota) { - resolve(batches); - } - }, interval); - }); + return batches; +}; + +module.exports.BatchAction = async function <I, O>(batchSize: number, handler: BatchHandler<I, O>, interval?: number): Promise<O[]> { + if (!this.length) { + return []; + } + let collector: O[] = []; + const batches = this.batch(batchSize); + if (!interval || batches.length === 1) { + for (let batch of batches) { + collector.push(...(await handler(batch))); } + } else { + return new Promise<O[]>(resolve => { + const iterator = batches[Symbol.iterator](); + let completed = 0; + const tag = setInterval(async () => { + const next = iterator.next(); + if (next.done) { + clearInterval(tag); + return; + } + const batch = next.value; + collector.push(...(await handler(batch))); + if (++completed === batches.length) { + resolve(collector); + } + }, interval); + }); } - return batches; + return collector; };
\ No newline at end of file |