forked from tjmehta/101
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-index.js
49 lines (44 loc) · 1.45 KB
/
find-index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* @module 101/find-index
*/
var isFunction = require('./is-function');
var exists = require('./exists');
/**
* Finds the first value in the list that passes the given function (predicate) and returns it's index.
* If list is not provided findIndex will return a partial-function which accepts a list as the first argument.
* @function module:101/find-index
* @param {array|string} [list] - list to be searched
* @param {array|string} predicate - executed on each item in the list and returns true when the item is found
* @return {number|function} Index of item which passes predicate or Partial isFunction (which accepts list)
*/
module.exports = function (list, predicate) {
if (exists(list && list.length) && !isFunction(list)) {
return findIndex(list, predicate);
}
else if (isFunction(list)) {
predicate = list;
return function (list) {
return findIndex(list, predicate);
};
}
else {
throw new TypeError('first argument must be a list (have length) or function');
}
};
function findIndex (list, predicate) {
if (!exists(list && list.length)) {
throw new TypeError('list must have length property');
}
if (!isFunction(predicate)) {
throw new TypeError('predicate must be a function');
}
var index = -1;
list = Array.prototype.slice.call(list); // cast as array to use some.
list.some(function (val, i) {
if (predicate(val, i, list)) {
index = i;
return true;
}
});
return index;
}