esnext.iterator.flat-map.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 getIteratorDirect = require('../internals/get-iterator-direct');
  7. var getIteratorFlattenable = require('../internals/get-iterator-flattenable');
  8. var createIteratorProxy = require('../internals/iterator-create-proxy');
  9. var iteratorClose = require('../internals/iterator-close');
  10. var IS_PURE = require('../internals/is-pure');
  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++), false);
  25. } catch (error) { iteratorClose(iterator, 'throw', error); }
  26. }
  27. });
  28. // `Iterator.prototype.flatMap` method
  29. // https://github.com/tc39/proposal-iterator-helpers
  30. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
  31. flatMap: function flatMap(mapper) {
  32. anObject(this);
  33. aCallable(mapper);
  34. return new IteratorProxy(getIteratorDirect(this), {
  35. mapper: mapper,
  36. inner: null
  37. });
  38. }
  39. });