esnext.iterator.chunks.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var anObject = require('../internals/an-object');
  4. var call = require('../internals/function-call');
  5. var createIteratorProxy = require('../internals/iterator-create-proxy');
  6. var getIteratorDirect = require('../internals/get-iterator-direct');
  7. var iteratorClose = require('../internals/iterator-close');
  8. var uncurryThis = require('../internals/function-uncurry-this');
  9. var $RangeError = RangeError;
  10. var push = uncurryThis([].push);
  11. var IteratorProxy = createIteratorProxy(function () {
  12. var iterator = this.iterator;
  13. var next = this.next;
  14. var chunkSize = this.chunkSize;
  15. var buffer = [];
  16. var result, done;
  17. while (true) {
  18. result = anObject(call(next, iterator));
  19. done = !!result.done;
  20. if (done) {
  21. if (buffer.length) return buffer;
  22. this.done = true;
  23. return;
  24. }
  25. push(buffer, result.value);
  26. if (buffer.length === chunkSize) return buffer;
  27. }
  28. });
  29. // `Iterator.prototype.chunks` method
  30. // https://github.com/tc39/proposal-iterator-chunking
  31. $({ target: 'Iterator', proto: true, real: true, forced: true }, {
  32. chunks: function chunks(chunkSize) {
  33. var O = anObject(this);
  34. if (typeof chunkSize != 'number' || !chunkSize || chunkSize >>> 0 !== chunkSize) {
  35. return iteratorClose(O, 'throw', new $RangeError('chunkSize must be integer in [1, 2^32-1]'));
  36. }
  37. return new IteratorProxy(getIteratorDirect(O), {
  38. chunkSize: chunkSize
  39. });
  40. }
  41. });