Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80742 views
1
var baseEach = require('../internal/baseEach'),
2
invokePath = require('../internal/invokePath'),
3
isArrayLike = require('../internal/isArrayLike'),
4
isKey = require('../internal/isKey'),
5
restParam = require('../function/restParam');
6
7
/**
8
* Invokes the method at `path` of each element in `collection`, returning
9
* an array of the results of each invoked method. Any additional arguments
10
* are provided to each invoked method. If `methodName` is a function it is
11
* invoked for, and `this` bound to, each element in `collection`.
12
*
13
* @static
14
* @memberOf _
15
* @category Collection
16
* @param {Array|Object|string} collection The collection to iterate over.
17
* @param {Array|Function|string} path The path of the method to invoke or
18
* the function invoked per iteration.
19
* @param {...*} [args] The arguments to invoke the method with.
20
* @returns {Array} Returns the array of results.
21
* @example
22
*
23
* _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
24
* // => [[1, 5, 7], [1, 2, 3]]
25
*
26
* _.invoke([123, 456], String.prototype.split, '');
27
* // => [['1', '2', '3'], ['4', '5', '6']]
28
*/
29
var invoke = restParam(function(collection, path, args) {
30
var index = -1,
31
isFunc = typeof path == 'function',
32
isProp = isKey(path),
33
result = isArrayLike(collection) ? Array(collection.length) : [];
34
35
baseEach(collection, function(value) {
36
var func = isFunc ? path : ((isProp && value != null) ? value[path] : null);
37
result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
38
});
39
return result;
40
});
41
42
module.exports = invoke;
43
44