esnext.iterator.flat-map.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 getIteratorDirect = require('../internals/get-iterator-direct');
  8. var getIteratorFlattenable = require('../internals/get-iterator-flattenable');
  9. var createIteratorProxy = require('../internals/iterator-create-proxy');
  10. var iteratorClose = require('../internals/iterator-close');
  11. var IteratorProxy = createIteratorProxy(function () {
  12. var iterator = this.iterator;
  13. var mapper = this.mapper;
  14. var result, inner;
  15. while (true) {
  16. if (inner = this.inner) try {
  17. result = anObject(call(inner.next, inner.iterator));
  18. if (!result.done) return result.value;
  19. this.inner = null;
  20. } catch (error) { iteratorClose(iterator, 'throw', error); }
  21. result = anObject(call(this.next, iterator));
  22. if (this.done = !!result.done) return;
  23. try {
  24. this.inner = getIteratorFlattenable(mapper(result.value, this.counter++));
  25. } catch (error) { iteratorClose(iterator, 'throw', error); }
  26. }
  27. });
  28. $({ target: 'Iterator', proto: true, real: true, forced: true }, {
  29. flatMap: function flatMap(mapper) {
  30. return new IteratorProxy(getIteratorDirect(this), {
  31. mapper: aCallable(mapper),
  32. inner: null
  33. });
  34. }
  35. });