1 | var baseFindIndex = require('./_baseFindIndex'),
|
---|
2 | baseIteratee = require('./_baseIteratee'),
|
---|
3 | toInteger = require('./toInteger');
|
---|
4 |
|
---|
5 | /* Built-in method references for those with the same name as other `lodash` methods. */
|
---|
6 | var nativeMax = Math.max;
|
---|
7 |
|
---|
8 | /**
|
---|
9 | * This method is like `_.find` except that it returns the index of the first
|
---|
10 | * element `predicate` returns truthy for instead of the element itself.
|
---|
11 | *
|
---|
12 | * @static
|
---|
13 | * @memberOf _
|
---|
14 | * @since 1.1.0
|
---|
15 | * @category Array
|
---|
16 | * @param {Array} array The array to inspect.
|
---|
17 | * @param {Function} [predicate=_.identity] The function invoked per iteration.
|
---|
18 | * @param {number} [fromIndex=0] The index to search from.
|
---|
19 | * @returns {number} Returns the index of the found element, else `-1`.
|
---|
20 | * @example
|
---|
21 | *
|
---|
22 | * var users = [
|
---|
23 | * { 'user': 'barney', 'active': false },
|
---|
24 | * { 'user': 'fred', 'active': false },
|
---|
25 | * { 'user': 'pebbles', 'active': true }
|
---|
26 | * ];
|
---|
27 | *
|
---|
28 | * _.findIndex(users, function(o) { return o.user == 'barney'; });
|
---|
29 | * // => 0
|
---|
30 | *
|
---|
31 | * // The `_.matches` iteratee shorthand.
|
---|
32 | * _.findIndex(users, { 'user': 'fred', 'active': false });
|
---|
33 | * // => 1
|
---|
34 | *
|
---|
35 | * // The `_.matchesProperty` iteratee shorthand.
|
---|
36 | * _.findIndex(users, ['active', false]);
|
---|
37 | * // => 0
|
---|
38 | *
|
---|
39 | * // The `_.property` iteratee shorthand.
|
---|
40 | * _.findIndex(users, 'active');
|
---|
41 | * // => 2
|
---|
42 | */
|
---|
43 | function findIndex(array, predicate, fromIndex) {
|
---|
44 | var length = array == null ? 0 : array.length;
|
---|
45 | if (!length) {
|
---|
46 | return -1;
|
---|
47 | }
|
---|
48 | var index = fromIndex == null ? 0 : toInteger(fromIndex);
|
---|
49 | if (index < 0) {
|
---|
50 | index = nativeMax(length + index, 0);
|
---|
51 | }
|
---|
52 | return baseFindIndex(array, baseIteratee(predicate, 3), index);
|
---|
53 | }
|
---|
54 |
|
---|
55 | module.exports = findIndex;
|
---|