All files reducer.js

100% Statements 13/13
100% Branches 2/2
100% Functions 3/3
100% Lines 13/13

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                                    2x 10x 10x 10x 44x   44x 9x 9x   35x 35x 34x   1x       10x    
/**
 * Execute an array of async functions in order
 * passing the result of each function to the next
 *
 * @async
 * @function reducer
 * @param  {*} startValue - The starting value
 * @param  {function[]} funcs - The async functions to execute
 * @returns {*} - The final value from the functions
 *
 * @example
 *
 * const results = await reducer(0,
 *   asyncFunction,
 *   asyncFunction2,
 *   asyncFunction3
 * )
 */
module.exports = (startValue, ...funcs) =>
  new Promise((resolve, reject) => {
    const iterator = funcs[Symbol.iterator]()
    const next = async total => {
      const el = iterator.next()
 
      if (el.done) {
        resolve(total)
        return
      }
      try {
        const result = await el.value(total)
        next(result)
      } catch (error) {
        return reject(error)
      }
    }
 
    next(startValue)
  })