# All files / src pool.ts

96.55% Statements 28/29
100% Branches 0/0
90.91% Functions 10/11
95.45% Lines 21/22

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

    1x
    1x
    1x

    1x

    6x
    6x
    6x

    6x

    6x
    12x
    6x
    6x

    11x
    6x
    6x

    12x
    12x
    12x
    12x
    6x

    1x
     export type RunTask<T> = (...args: T[]) => Promise<void>

    export interface QueueContent<T> {
      task: T
      resolve: () => void
      reject: (err?: any) => void
    }

    export class Pool<T> {
      queue: Array<QueueContent<T>> = []
      processing: Array<QueueContent<T>> = []

      constructor(private runTask: RunTask<T>, private limit: number) {}

      enqueue(task: T) {
        return new Promise<void>((resolve, reject) => {
          this.queue.push({
            task,
            resolve,
            reject
          })
          this.check()
        })
      }

      run(item: QueueContent<T>) {
        this.queue = this.queue.filter(v => v !== item)
        this.processing.push(item)
        this.runTask(item.task).then(
          () => {
            this.processing = this.processing.filter(v => v !== item)
            item.resolve()
            this.check()
          },
          err => item.reject(err)
        )
      }

      check() {
        const processingNum = this.processing.length
        const availableNum = this.limit - processingNum
        this.queue.slice(0, availableNum).forEach(item => {
          this.run(item)
        })
      }
    }