es.iterator.take.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var call = require('../internals/function-call');
  4. var anObject = require('../internals/an-object');
  5. var getIteratorDirect = require('../internals/get-iterator-direct');
  6. var notANaN = require('../internals/not-a-nan');
  7. var toPositiveInteger = require('../internals/to-positive-integer');
  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. if (!this.remaining--) {
  14. this.done = true;
  15. return iteratorClose(iterator, 'normal', undefined);
  16. }
  17. var result = anObject(call(this.next, iterator));
  18. var done = this.done = !!result.done;
  19. if (!done) return result.value;
  20. });
  21. // `Iterator.prototype.take` method
  22. // https://tc39.es/ecma262/#sec-iterator.prototype.take
  23. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE }, {
  24. take: function take(limit) {
  25. anObject(this);
  26. var remaining = toPositiveInteger(notANaN(+limit));
  27. return new IteratorProxy(getIteratorDirect(this), {
  28. remaining: remaining
  29. });
  30. }
  31. });