iterator-create-proxy.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. var call = require('../internals/function-call');
  3. var aCallable = require('../internals/a-callable');
  4. var anObject = require('../internals/an-object');
  5. var create = require('../internals/object-create');
  6. var createNonEnumerableProperty = require('../internals/create-non-enumerable-property');
  7. var redefineAll = require('../internals/redefine-all');
  8. var wellKnownSymbol = require('../internals/well-known-symbol');
  9. var InternalStateModule = require('../internals/internal-state');
  10. var getMethod = require('../internals/get-method');
  11. var IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;
  12. var ITERATOR_PROXY = 'IteratorProxy';
  13. var setInternalState = InternalStateModule.set;
  14. var getInternalState = InternalStateModule.getterFor(ITERATOR_PROXY);
  15. var TO_STRING_TAG = wellKnownSymbol('toStringTag');
  16. module.exports = function (nextHandler, IS_ITERATOR) {
  17. var IteratorProxy = function Iterator(state) {
  18. state.type = ITERATOR_PROXY;
  19. state.next = aCallable(state.iterator.next);
  20. state.done = false;
  21. state.ignoreArg = !IS_ITERATOR;
  22. setInternalState(this, state);
  23. };
  24. IteratorProxy.prototype = redefineAll(create(IteratorPrototype), {
  25. next: function next(arg) {
  26. var state = getInternalState(this);
  27. var args = arguments.length ? [state.ignoreArg ? undefined : arg] : IS_ITERATOR ? [] : [undefined];
  28. state.ignoreArg = false;
  29. var result = state.done ? undefined : call(nextHandler, state, args);
  30. return { done: state.done, value: result };
  31. },
  32. 'return': function (value) {
  33. var state = getInternalState(this);
  34. var iterator = state.iterator;
  35. state.done = true;
  36. var $$return = getMethod(iterator, 'return');
  37. return { done: true, value: $$return ? anObject(call($$return, iterator, value)).value : value };
  38. },
  39. 'throw': function (value) {
  40. var state = getInternalState(this);
  41. var iterator = state.iterator;
  42. state.done = true;
  43. var $$throw = getMethod(iterator, 'throw');
  44. if ($$throw) return call($$throw, iterator, value);
  45. throw value;
  46. }
  47. });
  48. if (!IS_ITERATOR) {
  49. createNonEnumerableProperty(IteratorProxy.prototype, TO_STRING_TAG, 'Generator');
  50. }
  51. return IteratorProxy;
  52. };