iterate.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var bind = require('../internals/function-bind-context');
  2. var call = require('../internals/function-call');
  3. var anObject = require('../internals/an-object');
  4. var tryToString = require('../internals/try-to-string');
  5. var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
  6. var lengthOfArrayLike = require('../internals/length-of-array-like');
  7. var isPrototypeOf = require('../internals/object-is-prototype-of');
  8. var getIterator = require('../internals/get-iterator');
  9. var getIteratorMethod = require('../internals/get-iterator-method');
  10. var iteratorClose = require('../internals/iterator-close');
  11. var $TypeError = TypeError;
  12. var Result = function (stopped, result) {
  13. this.stopped = stopped;
  14. this.result = result;
  15. };
  16. var ResultPrototype = Result.prototype;
  17. module.exports = function (iterable, unboundFunction, options) {
  18. var that = options && options.that;
  19. var AS_ENTRIES = !!(options && options.AS_ENTRIES);
  20. var IS_RECORD = !!(options && options.IS_RECORD);
  21. var IS_ITERATOR = !!(options && options.IS_ITERATOR);
  22. var INTERRUPTED = !!(options && options.INTERRUPTED);
  23. var fn = bind(unboundFunction, that);
  24. var iterator, iterFn, index, length, result, next, step;
  25. var stop = function (condition) {
  26. if (iterator) iteratorClose(iterator, 'normal', condition);
  27. return new Result(true, condition);
  28. };
  29. var callFn = function (value) {
  30. if (AS_ENTRIES) {
  31. anObject(value);
  32. return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
  33. } return INTERRUPTED ? fn(value, stop) : fn(value);
  34. };
  35. if (IS_RECORD) {
  36. iterator = iterable.iterator;
  37. } else if (IS_ITERATOR) {
  38. iterator = iterable;
  39. } else {
  40. iterFn = getIteratorMethod(iterable);
  41. if (!iterFn) throw $TypeError(tryToString(iterable) + ' is not iterable');
  42. // optimisation for array iterators
  43. if (isArrayIteratorMethod(iterFn)) {
  44. for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
  45. result = callFn(iterable[index]);
  46. if (result && isPrototypeOf(ResultPrototype, result)) return result;
  47. } return new Result(false);
  48. }
  49. iterator = getIterator(iterable, iterFn);
  50. }
  51. next = IS_RECORD ? iterable.next : iterator.next;
  52. while (!(step = call(next, iterator)).done) {
  53. try {
  54. result = callFn(step.value);
  55. } catch (error) {
  56. iteratorClose(iterator, 'throw', error);
  57. }
  58. if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
  59. } return new Result(false);
  60. };