All files / src/sdk/utils/base batchProcessor.ts

100% Statements 19/19
71.42% Branches 5/7
100% Functions 4/4
100% Lines 18/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 3916x 16x       16x             16x 16x 16x 16x       171x 171x 1x 170x 75x         67x 67x 67x   67x 67x 67x        
export class BatchProcessor {
  private batch: unknown[] = [];
  private time: number;
  private batchSize: number;
  private processBatchCallback: (data: unknown[]) => void;
  private timer: NodeJS.Timeout | null = null;
 
  constructor(
    time: number = 2000,
    batchSize: number = 100,
    processBatchCallback: (data: unknown[]) => void
  ) {
    this.batch = [];
    this.time = time;
    this.batchSize = batchSize;
    this.processBatchCallback = processBatchCallback;
  }
 
  pushItem(item: unknown) {
    this.batch.push(item);
    if (this.batch.length >= this.batchSize) {
      this.processBatch();
    } else if (!this.timer) {
      this.timer = setTimeout(() => this.processBatch(), this.time);
    }
  }
 
  processBatch() {
    if (this.batch.length > 0) {
      this.processBatchCallback(this.batch);
      this.batch = [];
    }
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  }
}