Skip to content

Commit

Permalink
refactor(util): simplify objsToDict
Browse files Browse the repository at this point in the history
  • Loading branch information
arildm committed Jul 16, 2024
1 parent 7a98a0b commit d26a31b
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,9 @@ export const getFilenameExtension = (filename: string) =>
/** If an array, return first element. Otherwise return the whole argument. */
export const unarray = <T>(x: T[] | T): T => (Array.isArray(x) ? x[0] : x);

/** Create {a: A, b: B} from [ {k: a, v: A}, {k: b, v: B} ] */
/** Create dictionary by picking a key and a value from each object in a list. */
export const objsToDict = <
T extends Record<keyof any, any>,
T extends Record<K1 | K2, any>,
K1 extends keyof T,
K2 extends keyof T,
>(
Expand All @@ -138,12 +138,9 @@ export const objsToDict = <
valueName: K2,
): Record<T[K1], T[K2]> =>
objs.reduce(
(dict: Partial<Record<T[K1], T[K2]>>, item) => ({
...dict,
[item[keyName]]: item[valueName],
}),
{},
) as Record<T[K1], T[K2]>;
(dict, item) => ({ ...dict, [item[keyName]]: item[valueName] }),
{} as Record<T[K1], T[K2]>,
);

/** Like lodash/keyBy but slightly more restrictive in range and typing. */
export const keyBy = <T extends Record<K, keyof any>, K extends keyof T>(
Expand Down

0 comments on commit d26a31b

Please sign in to comment.