esnext.async-iterator.reduce.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var aCallable = require('../internals/a-callable');
  5. var anObject = require('../internals/an-object');
  6. var isObject = require('../internals/is-object');
  7. var getBuiltIn = require('../internals/get-built-in');
  8. var getIteratorDirect = require('../internals/get-iterator-direct');
  9. var closeAsyncIteration = require('../internals/async-iterator-close');
  10. var Promise = getBuiltIn('Promise');
  11. var $TypeError = TypeError;
  12. // `AsyncIterator.prototype.reduce` method
  13. // https://github.com/tc39/proposal-async-iterator-helpers
  14. $({ target: 'AsyncIterator', proto: true, real: true }, {
  15. reduce: function reduce(reducer /* , initialValue */) {
  16. anObject(this);
  17. aCallable(reducer);
  18. var record = getIteratorDirect(this);
  19. var iterator = record.iterator;
  20. var next = record.next;
  21. var noInitial = arguments.length < 2;
  22. var accumulator = noInitial ? undefined : arguments[1];
  23. var counter = 0;
  24. return new Promise(function (resolve, reject) {
  25. var ifAbruptCloseAsyncIterator = function (error) {
  26. closeAsyncIteration(iterator, reject, error, reject);
  27. };
  28. var loop = function () {
  29. try {
  30. Promise.resolve(anObject(call(next, iterator))).then(function (step) {
  31. try {
  32. if (anObject(step).done) {
  33. noInitial ? reject(new $TypeError('Reduce of empty iterator with no initial value')) : resolve(accumulator);
  34. } else {
  35. var value = step.value;
  36. if (noInitial) {
  37. noInitial = false;
  38. accumulator = value;
  39. loop();
  40. } else try {
  41. var result = reducer(accumulator, value, counter);
  42. var handler = function ($result) {
  43. accumulator = $result;
  44. loop();
  45. };
  46. if (isObject(result)) Promise.resolve(result).then(handler, ifAbruptCloseAsyncIterator);
  47. else handler(result);
  48. } catch (error3) { ifAbruptCloseAsyncIterator(error3); }
  49. }
  50. counter++;
  51. } catch (error2) { reject(error2); }
  52. }, reject);
  53. } catch (error) { reject(error); }
  54. };
  55. loop();
  56. });
  57. }
  58. });