All files / src/runQueue runQueue.js

0% Statements 0/17
0% Branches 0/12
0% Functions 0/2
0% Lines 0/15

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                                                                                   
const chalk = require('chalk');
const { InvalidTypeError } = require('../errors');
 
/**
 * @typedef {Object} Task
 * @property {boolean | undefined} executed If the task was already executed once.
 * @property {string | undefined} label The task label for console output.
 * @property {function} task The task function to be executed.
 */
 
/**
 * Run a queue of task functions in order.
 *
 * @param {Task[]} tasks An array of Task objects.
 * @returns {undefined}
 * @throws {InvalidTypeError} if type of tasks is not an array or task item is not a a function.
 */
async function runQueue(tasks) {
  if (!tasks || !Array.isArray(tasks)) {
    throw new InvalidTypeError('tasks', tasks, 'object (Array)');
  }
 
  if (!this.current) this.current = 0;
  if (this.current >= tasks.length) return;
 
  const { label, task } = tasks[this.current];
 
  console.log(chalk.green(`[${this.current + 1}/${tasks.length}] ${label}`));
 
  if (!task || typeof task !== 'function') {
    throw new InvalidTypeError(`task[${this.current}]`, task, 'function');
  }
 
  await task(() => {
    tasks[this.current].executed = true;
    this.current += 1;
    runQueue(tasks);
  });
}
 
module.exports = { runQueue };