UNPKG

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