esnext.iterator.flat-map.js 1.7 KB

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