iterate.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');
  7. var Result = function (stopped, result) {
  8. this.stopped = stopped;
  9. this.result = result;
  10. };
  11. var iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) {
  12. var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1);
  13. var iterator, iterFn, index, length, result, next, step;
  14. if (IS_ITERATOR) {
  15. iterator = iterable;
  16. } else {
  17. iterFn = getIteratorMethod(iterable);
  18. if (typeof iterFn != 'function') throw TypeError('Target is not iterable');
  19. // optimisation for array iterators
  20. if (isArrayIteratorMethod(iterFn)) {
  21. for (index = 0, length = toLength(iterable.length); length > index; index++) {
  22. result = AS_ENTRIES
  23. ? boundFunction(anObject(step = iterable[index])[0], step[1])
  24. : boundFunction(iterable[index]);
  25. if (result && result instanceof Result) return result;
  26. } return new Result(false);
  27. }
  28. iterator = iterFn.call(iterable);
  29. }
  30. next = iterator.next;
  31. while (!(step = next.call(iterator)).done) {
  32. result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES);
  33. if (typeof result == 'object' && result && result instanceof Result) return result;
  34. } return new Result(false);
  35. };
  36. iterate.stop = function (result) {
  37. return new Result(true, result);
  38. };