invokeMap
collection
Invokes the method at path of each element in collection, returning an array of the results of each invoked method.
Installation
Import
import { invokeMap } from '@tulx/utils';Source Code
Implementation
/**
* Invokes the method at path of each element in collection, returning an array of the results of each invoked method.
*
* @param collection - The collection to iterate over.
* @param path - The path of the method to invoke or the function invoked per iteration.
* @param args - The arguments to invoke each method with.
* @returns Returns the array of results.
*
* @example
* ```ts
* invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); // [[1, 5, 7], [1, 2, 3]]
* invokeMap([123, 456], String.prototype.split, ['']); // [['1', '2', '3'], ['4', '5', '6']]
* ```
*/
export function invokeMap<T, TResult>(
collection: readonly T[] | Record<string, T>,
path: string | ((value: T) => unknown),
...args: readonly unknown[]
): TResult[] {
const result: TResult[] = [];
const items = Array.isArray(collection)
? collection
: Object.values(collection);
for (const item of items) {
let method: unknown;
if (typeof path === 'string') {
const pathParts = path.split('.');
let current: unknown = item;
for (const part of pathParts) {
if (current && typeof current === 'object' && part in current) {
current = (current as Record<string, unknown>)[part];
} else {
current = undefined;
break;
}
}
method = current;
} else {
method = path(item);
}
if (typeof method === 'function') {
result.push(method.apply(item, args) as TResult);
} else {
result.push(undefined as unknown as TResult);
}
}
return result;
}
Example
import { invokeMap } from '@tulx/utils';
invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); // [[1, 5, 7], [1, 2, 3]]
invokeMap([123, 456], String.prototype.split, ['']); // [['1', '2', '3'], ['4', '5', '6']]Related Functions
countBy
Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
each
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
eachRight
This method is like each except that it iterates over elements of collection from right to left.
every
Checks if predicate returns truthy for all elements of collection.
filter
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
find
Iterates over elements of collection, returning the first element predicate returns truthy for.