UNPKG

1.58 kBJavaScriptView Raw
1var apply = require('./_apply'),
2 baseEach = require('./_baseEach'),
3 baseInvoke = require('./_baseInvoke'),
4 baseRest = require('./_baseRest'),
5 isArrayLike = require('./isArrayLike'),
6 isKey = require('./_isKey');
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 `path` is a function, it's invoked
12 * 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 = baseRest(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
44module.exports = invokeMap;