index.js 413 B

12345678910111213141516171819202122
  1. 'use strict';
  2. module.exports = (iterable, reducer, initVal) => new Promise((resolve, reject) => {
  3. const iterator = iterable[Symbol.iterator]();
  4. let i = 0;
  5. const next = total => {
  6. const el = iterator.next();
  7. if (el.done) {
  8. resolve(total);
  9. return;
  10. }
  11. Promise.all([total, el.value])
  12. .then(value => {
  13. next(reducer(value[0], value[1], i++));
  14. })
  15. .catch(reject);
  16. };
  17. next(initVal);
  18. });