All files / rpc-calls/src/caller/util TimedQueue.ts

100% Statements 21/21
100% Branches 8/8
80% Functions 4/5
100% Lines 19/19

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 39 40 41 42 43 44 45 46        3x       42x         42x         42x   42x 42x     144x 144x 3x 3x   141x 55x 47x           56x 56x 56x 56x 56x 56x      
/**
 * Queue that is flushed automatically when it reaches some item limit
 * or when timeout is reached.
 */
export class TimedQueue<T> {
  /**
   * Queue will be flushed when it reaches this number of items.
   */
  public itemLimit = 100;
 
  /**
   * Queue will be flushed after this many milliseconds.
   */
  public timeLimit = 5;
 
  /**
   * Method that will be called when queue is flushed.
   */
  public onFlush: (list: T[]) => void = () => {};
 
  private list: T[] = [];
  private timer: null | number | NodeJS.Timeout = null;
 
  public push(item: T) {
    this.list.push(item);
    if (this.list.length >= this.itemLimit) {
      this.flush();
      return;
    }
    if (!this.timer) {
      this.timer = setTimeout(() => {
        this.flush();
      }, this.timeLimit);
    }
  }
 
  public flush(): T[] {
    const list = this.list;
    this.list = [];
    if (this.timer) clearTimeout(this.timer as any);
    this.timer = null;
    if (list.length) this.onFlush(list);
    return list;
  }
}