iterate.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var global = require('../internals/global');
  2. var bind = require('../internals/function-bind-context');
  3. var call = require('../internals/function-call');
  4. var anObject = require('../internals/an-object');
  5. var tryToString = require('../internals/try-to-string');
  6. var isArrayIteratorMethod = require('../internals/is-array-iterator-method');
  7. var lengthOfArrayLike = require('../internals/length-of-array-like');
  8. var isPrototypeOf = require('../internals/object-is-prototype-of');
  9. var getIterator = require('../internals/get-iterator');
  10. var getIteratorMethod = require('../internals/get-iterator-method');
  11. var iteratorClose = require('../internals/iterator-close');
  12. var TypeError = global.TypeError;
  13. var Result = function (stopped, result) {
  14. this.stopped = stopped;
  15. this.result = result;
  16. };
  17. var ResultPrototype = Result.prototype;
  18. module.exports = function (iterable, unboundFunction, options) {
  19. var that = options && options.that;
  20. var AS_ENTRIES = !!(options && options.AS_ENTRIES);
  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_ITERATOR) {
  36. iterator = iterable;
  37. } else {
  38. iterFn = getIteratorMethod(iterable);
  39. if (!iterFn) throw TypeError(tryToString(iterable) + ' is not iterable');
  40. // optimisation for array iterators
  41. if (isArrayIteratorMethod(iterFn)) {
  42. for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
  43. result = callFn(iterable[index]);
  44. if (result && isPrototypeOf(ResultPrototype, result)) return result;
  45. } return new Result(false);
  46. }
  47. iterator = getIterator(iterable, iterFn);
  48. }
  49. next = iterator.next;
  50. while (!(step = call(next, iterator)).done) {
  51. try {
  52. result = callFn(step.value);
  53. } catch (error) {
  54. iteratorClose(iterator, 'throw', error);
  55. }
  56. if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
  57. } return new Result(false);
  58. };