esnext.iterator.flat-map.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. // https://github.com/tc39/proposal-iterator-helpers
  3. var $ = require('../internals/export');
  4. var aFunction = require('../internals/a-function');
  5. var anObject = require('../internals/an-object');
  6. var getIteratorMethod = require('../internals/get-iterator-method');
  7. var createIteratorProxy = require('../internals/iterator-create-proxy');
  8. var iteratorClose = require('../internals/iterator-close');
  9. var IteratorProxy = createIteratorProxy(function () {
  10. var iterator = this.iterator;
  11. var mapper = this.mapper;
  12. var result, mapped, iteratorMethod, innerIterator;
  13. while (true) {
  14. try {
  15. if (innerIterator = this.innerIterator) {
  16. result = anObject(this.innerNext.call(innerIterator));
  17. if (!result.done) return result.value;
  18. this.innerIterator = this.innerNext = null;
  19. }
  20. result = anObject(this.next.call(iterator));
  21. if (this.done = !!result.done) return;
  22. mapped = mapper(result.value);
  23. iteratorMethod = getIteratorMethod(mapped);
  24. if (iteratorMethod === undefined) {
  25. throw TypeError('.flatMap callback should return an iterable object');
  26. }
  27. this.innerIterator = innerIterator = anObject(iteratorMethod.call(mapped));
  28. this.innerNext = aFunction(innerIterator.next);
  29. } catch (error) {
  30. iteratorClose(iterator, 'throw', error);
  31. }
  32. }
  33. });
  34. $({ target: 'Iterator', proto: true, real: true }, {
  35. flatMap: function flatMap(mapper) {
  36. return new IteratorProxy({
  37. iterator: anObject(this),
  38. mapper: aFunction(mapper),
  39. innerIterator: null,
  40. innerNext: null
  41. });
  42. }
  43. });