-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f0e06ba
commit 630f9ef
Showing
4 changed files
with
63 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,39 @@ | ||
/** | ||
* Map over all the keys to create a new object | ||
*/ | ||
export const mapValues = < | ||
export function mapValues< | ||
TValue, | ||
TKey extends string | number | symbol, | ||
TNewValue | ||
>( | ||
obj: Record<TKey, TValue>, | ||
obj: { [K in TKey]: TValue }, | ||
mapFunc: (value: TValue, key: TKey) => TNewValue | ||
): Record<TKey, TNewValue> => { | ||
): { [K in TKey]: TNewValue } | ||
|
||
// This overload exists to support cases where `obj` is a partial | ||
// object whose values are never undefined when the key is also | ||
// defined. For example: | ||
// { [key: string]?: number } versus { [key: string]: number | undefined } | ||
export function mapValues< | ||
TValue, | ||
TKey extends string | number | symbol, | ||
TNewValue | ||
>( | ||
obj: { [K in TKey]?: TValue }, | ||
mapFunc: (value: TValue, key: TKey) => TNewValue | ||
): { [K in TKey]?: TNewValue } | ||
|
||
export function mapValues< | ||
TValue, | ||
TKey extends string | number | symbol, | ||
TNewValue | ||
>( | ||
obj: { [K in TKey]?: TValue }, | ||
mapFunc: (value: TValue, key: TKey) => TNewValue | ||
): Record<TKey, TNewValue> { | ||
const keys = Object.keys(obj) as TKey[] | ||
return keys.reduce((acc, key) => { | ||
acc[key] = mapFunc(obj[key], key) | ||
acc[key] = mapFunc(obj[key]!, key) | ||
return acc | ||
}, {} as Record<TKey, TNewValue>) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters