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