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');
13 var TypeError = global.TypeError;
15 var Result = function (stopped, result) {
16 this.stopped = stopped;
20 var ResultPrototype = Result.prototype;
22 module.exports = function (iterable, unboundFunction, options) {
23 var that = options && options.that;
24 var AS_ENTRIES = !!(options && options.AS_ENTRIES);
25 var IS_ITERATOR = !!(options && options.IS_ITERATOR);
26 var INTERRUPTED = !!(options && options.INTERRUPTED);
27 var fn = bind(unboundFunction, that);
28 var iterator, iterFn, index, length, result, next, step;
30 var stop = function (condition) {
31 if (iterator) iteratorClose(iterator, 'normal', condition);
32 return new Result(true, condition);
35 var callFn = function (value) {
38 return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);
39 } return INTERRUPTED ? fn(value, stop) : fn(value);
45 iterFn = getIteratorMethod(iterable);
46 if (!iterFn) throw TypeError(tryToString(iterable) + ' is not iterable');
47 // optimisation for array iterators
48 if (isArrayIteratorMethod(iterFn)) {
49 for (index = 0, length = lengthOfArrayLike(iterable); length > index; index++) {
50 result = callFn(iterable[index]);
51 if (result && isPrototypeOf(ResultPrototype, result)) return result;
52 } return new Result(false);
54 iterator = getIterator(iterable, iterFn);
58 while (!(step = call(next, iterator)).done) {
60 result = callFn(step.value);
62 iteratorClose(iterator, 'throw', error);
64 if (typeof result == 'object' && result && isPrototypeOf(ResultPrototype, result)) return result;
65 } return new Result(false);