esnext.iterator.flat-map.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
  9. var IteratorProxy = createIteratorProxy(function (arg) {
  10. var iterator = this.iterator;
  11. var result, mapped, iteratorMethod, innerIterator;
  12. while (true) {
  13. if (innerIterator = this.innerIterator) {
  14. result = anObject(this.innerNext.call(innerIterator));
  15. if (!result.done) return result.value;
  16. this.innerIterator = this.innerNext = null;
  17. }
  18. result = anObject(this.next.call(iterator, arg));
  19. if (this.done = !!result.done) return;
  20. mapped = callWithSafeIterationClosing(iterator, this.mapper, result.value);
  21. iteratorMethod = getIteratorMethod(mapped);
  22. if (iteratorMethod === undefined) {
  23. throw TypeError('.flatMap callback should return an iterable object');
  24. }
  25. this.innerIterator = innerIterator = anObject(iteratorMethod.call(mapped));
  26. this.innerNext = aFunction(innerIterator.next);
  27. }
  28. });
  29. $({ target: 'Iterator', proto: true, real: true }, {
  30. flatMap: function flatMap(mapper) {
  31. return new IteratorProxy({
  32. iterator: anObject(this),
  33. mapper: aFunction(mapper),
  34. innerIterator: null,
  35. innerNext: null
  36. });
  37. }
  38. });