UNPKG

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