map
collection
Creates an array of values by running each element in collection thru iteratee.
Installation
Import
import { map } from '@tulx/utils';Source Code
Implementation
/**
* Creates an array of values by running each element in collection thru iteratee.
*
* @param collection - The collection to iterate over.
* @param iteratee - The function invoked per iteration.
* @returns Returns the new mapped array.
*
* @example
* ```ts
* function square(n: number) {
* return n * n;
* }
* map([4, 8], square); // [16, 64]
* map({ 'a': 4, 'b': 8 }, square); // [16, 64]
* ```
*/
export function map<T, TResult>(
collection: readonly T[] | Record<string, T>,
iteratee: (
value: T,
index: number | string,
collection: readonly T[] | Record<string, T>
) => TResult
): TResult[] {
const result: TResult[] = [];
if (Array.isArray(collection)) {
for (let i = 0; i < collection.length; i++) {
result.push(iteratee(collection[i], i, collection));
}
} else {
const record = collection as Record<string, T>;
for (const key in record) {
if (Object.prototype.hasOwnProperty.call(record, key)) {
result.push(iteratee(record[key], key, record));
}
}
}
return result;
}
Example
import { map } from '@tulx/utils';
function square(n: number) {
return n * n;
}
map([4, 8], square); // [16, 64]
map({ 'a': 4, 'b': 8 }, square); // [16, 64]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.