|
| 1 | +/* |
| 2 | + * @nevware21/ts-utils |
| 3 | + * https://github.com/nevware21/ts-utils |
| 4 | + * |
| 5 | + * Copyright (c) 2026 NevWare21 Solutions LLC |
| 6 | + * Licensed under the MIT license. |
| 7 | + */ |
| 8 | + |
| 9 | +import { isArrayLike } from "../helpers/base"; |
| 10 | +import { isUnsafePropKey } from "../object/isUnsafePropKey"; |
| 11 | +import { iterForOf } from "../iterator/forOf"; |
| 12 | +import { ArrToMapKeySelectorFn, ArrToMapValueSelectorFn } from "../iterator/types"; |
| 13 | +import { arrForEach } from "./forEach"; |
| 14 | + |
| 15 | +/** |
| 16 | + * Creates an object map from array-like, iterator or iterable values. |
| 17 | + * |
| 18 | + * Keys are generated in stable source order via `keySelector`; later duplicate keys overwrite earlier values. |
| 19 | + * Unsafe keys (`__proto__`, `constructor`, `prototype`) are ignored. |
| 20 | + * @since 0.15.0 |
| 21 | + * @group Array |
| 22 | + * @example |
| 23 | + * ```ts |
| 24 | + * const users = [ |
| 25 | + * { id: "u1", name: "Ada" }, |
| 26 | + * { id: "u2", name: "Lin" }, |
| 27 | + * { id: "u1", name: "Ada Updated" } |
| 28 | + * ]; |
| 29 | + * |
| 30 | + * arrToMap(users, (value) => value.id, (value) => value.name); |
| 31 | + * // { u1: "Ada Updated", u2: "Lin" } |
| 32 | + * ``` |
| 33 | + */ |
| 34 | +/*#__NO_SIDE_EFFECTS__*/ |
| 35 | +export function arrToMap<T>(values: ArrayLike<T> | Iterator<T> | Iterable<T>, keySelector: ArrToMapKeySelectorFn<T>): { [key: string]: T }; |
| 36 | +/*#__NO_SIDE_EFFECTS__*/ |
| 37 | +export function arrToMap<T, V>(values: ArrayLike<T> | Iterator<T> | Iterable<T>, keySelector: ArrToMapKeySelectorFn<T>, valueSelector: ArrToMapValueSelectorFn<T, V>): { [key: string]: V }; |
| 38 | +/*#__NO_SIDE_EFFECTS__*/ |
| 39 | +export function arrToMap<T, V = T>(values: ArrayLike<T> | Iterator<T> | Iterable<T>, keySelector: ArrToMapKeySelectorFn<T>, valueSelector?: ArrToMapValueSelectorFn<T, V>): { [key: string]: V } { |
| 40 | + let result: { [key: string]: V } = {}; |
| 41 | + |
| 42 | + function _processValue(value: T, index?: number) { |
| 43 | + let valueIndex = index || 0; |
| 44 | + let key = keySelector(value, valueIndex); |
| 45 | + let keyValue = key + ""; |
| 46 | + if (!isUnsafePropKey(keyValue)) { |
| 47 | + result[keyValue] = valueSelector ? valueSelector(value, valueIndex) : (value as any as V); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if (isArrayLike(values)) { |
| 52 | + arrForEach(values, _processValue); |
| 53 | + } else { |
| 54 | + iterForOf(values as Iterator<T> | Iterable<T>, _processValue); |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | + return result; |
| 59 | +} |
0 commit comments