esnext.async-iterator.reduce.js 1.7 KB

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