esnext.async-iterator.reduce.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. // https://github.com/tc39/proposal-iterator-helpers
  3. var $ = require('../internals/export');
  4. var aFunction = require('../internals/a-function');
  5. var anObject = require('../internals/an-object');
  6. var getBuiltIn = require('../internals/get-built-in');
  7. var Promise = getBuiltIn('Promise');
  8. $({ target: 'AsyncIterator', proto: true, real: true }, {
  9. reduce: function reduce(reducer /* , initialValue */) {
  10. var iterator = anObject(this);
  11. var next = aFunction(iterator.next);
  12. var noInitial = arguments.length < 2;
  13. var accumulator = noInitial ? undefined : arguments[1];
  14. aFunction(reducer);
  15. return new Promise(function (resolve, reject) {
  16. var loop = function () {
  17. try {
  18. Promise.resolve(anObject(next.call(iterator))).then(function (step) {
  19. try {
  20. if (anObject(step).done) {
  21. noInitial ? reject(TypeError('Reduce of empty iterator with no initial value')) : resolve(accumulator);
  22. } else {
  23. var value = step.value;
  24. if (noInitial) {
  25. noInitial = false;
  26. accumulator = value;
  27. loop();
  28. } else {
  29. Promise.resolve(reducer(accumulator, value)).then(function (result) {
  30. accumulator = result;
  31. loop();
  32. }, reject);
  33. }
  34. }
  35. } catch (err) { reject(err); }
  36. }, reject);
  37. } catch (error) { reject(error); }
  38. };
  39. loop();
  40. });
  41. }
  42. });