es.iterator.take.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 iteratorHelperWithoutClosingOnEarlyError = require('../internals/iterator-helper-without-closing-on-early-error');
  11. var IS_PURE = require('../internals/is-pure');
  12. var takeWithoutClosingOnEarlyError = !IS_PURE && iteratorHelperWithoutClosingOnEarlyError('take', RangeError);
  13. var IteratorProxy = createIteratorProxy(function () {
  14. var iterator = this.iterator;
  15. if (!this.remaining--) {
  16. this.done = true;
  17. return iteratorClose(iterator, 'normal', undefined);
  18. }
  19. var result = anObject(call(this.next, iterator));
  20. var done = this.done = !!result.done;
  21. if (!done) return result.value;
  22. });
  23. // `Iterator.prototype.take` method
  24. // https://tc39.es/ecma262/#sec-iterator.prototype.take
  25. $({ target: 'Iterator', proto: true, real: true, forced: IS_PURE || takeWithoutClosingOnEarlyError }, {
  26. take: function take(limit) {
  27. anObject(this);
  28. var remaining;
  29. try {
  30. remaining = toPositiveInteger(notANaN(+limit));
  31. } catch (error) {
  32. iteratorClose(this, 'throw', error);
  33. }
  34. if (takeWithoutClosingOnEarlyError) return call(takeWithoutClosingOnEarlyError, this, remaining);
  35. return new IteratorProxy(getIteratorDirect(this), {
  36. remaining: remaining
  37. });
  38. }
  39. });