Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 8x 8x 2x 8x 2x 6x 6x 4x 6x | import { PredIndexedOptional } from './_types';
import { purry } from './purry';
/**
* Map each element of an array into an object using a defined callback function and flatten the result.
* @param array The array to map.
* @param fn The mapping function, which should return an Array of key-value pairs, similar to Object.fromEntries
* @returns The new mapped object.
* @signature
* P.flatMapToObj(array, fn)
* P.flatMapToObj.indexed(array, fn)
* @example
* P.flatMapToObj([1, 2, 3], (x) =>
* x % 2 === 1 ? [[String(x), x]] : []
* ) // => {1: 1, 3: 3}
* P.flatMapToObj.indexed(['a', 'b'], (x, i) => [
* [x, i],
* [x + x, i + i],
* ]) // => {a: 0, aa: 0, b: 1, bb: 2}
* @data_first
* @indexed
* @category Array
*/
export function flatMapToObj<T, K extends string | number | symbol, V>(
array: readonly T[],
fn: (element: T, index: number, array: readonly T[]) => [K, V][]
): Record<K, V>;
/**
* Map each element of an array into an object using a defined callback function and flatten the result.
* @param fn The mapping function, which should return an Array of key-value pairs, similar to Object.fromEntries
* @returns The new mapped object.
* @signature
* P.flatMapToObj(fn)(array)
* P.flatMapToObj(fn)(array)
* @example
* P.pipe(
* [1, 2, 3],
* P.flatMapToObj(x => (x % 2 === 1 ? [[String(x), x]] : []))
* ) // => {1: 1, 3: 3}
* P.pipe(
* ['a', 'b'],
* P.flatMapToObj.indexed((x, i) => [
* [x, i],
* [x + x, i + i],
* ])
* ) // => {a: 0, aa: 0, b: 1, bb: 2}
* @data_last
* @indexed
* @category Array
*/
export function flatMapToObj<T, K extends string | number | symbol, V>(
fn: (element: T, index: number, array: readonly T[]) => [K, V][]
): (array: readonly T[]) => Record<K, V>;
export function flatMapToObj() {
return purry(_flatMapToObj(), arguments);
}
const _flatMapToObj = () => <T>(
array: any[],
fn: PredIndexedOptional<any, any>
) => {
return array.reduce((result, element, index) => {
const items = fn(element, index, array);
items.forEach(([key, value]: [any, any]) => {
result[key] = value;
});
return result;
}, {});
};
|