iterate.js 2.0 KB

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