UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

49 lines (47 loc) 1.16 kB
import { dfdlT } from "@monstermann/dfdl"; //#region src/array/indexBy.ts /** * `indexBy(target, by, transform?)` * * Creates a record by indexing the `target` array using the `by` function to generate keys. Optionally transforms values using the `transform` function. * * ```ts * const users = [ * { id: 1, name: "Alice" }, * { id: 2, name: "Bob" }, * ]; * * indexBy(users, (user) => user.id); * // { 1: { id: 1, name: 'Alice' }, 2: { id: 2, name: 'Bob' } } * * indexBy( * users, * (user) => user.id, * (user) => user.name, * ); // { 1: "Alice", 2: "Bob" } * ``` * * ```ts * pipe( * users, * indexBy((user) => user.id), * ); // { 1: { id: 1, name: 'Alice' }, 2: { id: 2, name: 'Bob' } } * * pipe( * users, * indexBy( * (user) => user.id, * (user) => user.name, * ), * ); // { 1: "Alice", 2: "Bob" } * ``` */ const indexBy = dfdlT((target, by, transform) => { return target.reduce((acc, value, idx) => { const key = by(value, idx, target); acc[key] = transform ? transform(value, key, idx, target) : value; return acc; }, {}); }, (args) => Array.isArray(args[0])); //#endregion export { indexBy };