esnext.async-iterator.reduce.js 2.2 KB

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