All files / sdk/utils/base batchProcessor.ts

94.73% Statements 18/19
57.14% Branches 4/7
100% Functions 4/4
94.44% Lines 17/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 3915x 15x       15x             15x 15x 15x 15x       157x 157x   157x 73x         68x 68x 68x   68x 68x 68x        
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);
    Iif (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;
    }
  }
}