All files TimedQueue.ts

96% Statements 24/25
100% Branches 8/8
80% Functions 4/5
96% Lines 24/25

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 47 48 49 50 51 52 53  1x 1x                   9x       9x       9x 9x 9x     24x 24x 3x 3x   21x 13x 5x         14x 14x 14x 13x 14x 14x 13x 13x             14x  
/**
 * 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.
   */
  itemLimit: number = 100;
 
  /**
   * Queue will be flushed after this many milliseconds.
   */
  timeLimit: number = 5_000;
 
  /**
   * Method that will be called when queue is flushed.
   */
  onFlush = (list: T[]) => {};
 
  private list: T[] = [];
  private timer: any = null;
 
  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);
    }
  }
 
  flush(): T[] {
    const list = this.list;
    this.list = [];
    if (this.timer) clearTimeout(this.timer);
    this.timer = null;
    if (list.length) {
      try {
        this.onFlush(list);
      } catch (error) {
        // tslint:disable-next-line
        console.error('TimedQueue', error);
      }
    }
    return list;
  }
}