-
Notifications
You must be signed in to change notification settings - Fork 75
/
find-index.js
53 lines (48 loc) · 1.62 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
50
51
52
53
/**
* @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 {function} predicate - executed on each item in the list and returns true when the item is found
* @return {number} - index of first item which passes predicate
*
* @param {function} predicate - executed on each item in the list and returns true when the item is found
* @return {function} - partial function (accepts list and returns index of first item that passes predicate)
*/
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;
}