Last active
March 4, 2023 12:52
-
-
Save haggen/6a5f1bbb60828695e85af0f94821e8a5 to your computer and use it in GitHub Desktop.
Map function in TypeScript that works for Arrays as well as Objects.
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
/** | |
* Unknown array type alias. | |
*/ | |
type TArray = unknown[]; | |
/** | |
* Unknown object type alias. | |
*/ | |
type TObject = Record<string | symbol, unknown>; | |
/** | |
* Mapable collection. | |
*/ | |
export type Mapable = TArray | TObject; | |
/** | |
* Mapper function. | |
*/ | |
export type Mapper<T extends Mapable, U> = T extends TArray | |
? (value: T[number], key: number, collection: T) => U | |
: (value: T[keyof T], key: keyof T, collection: T) => U; | |
/** | |
* Map arrays and objects alike. | |
*/ | |
export function map<T extends TArray, U>(collection: T, map: Mapper<T, U>): U[]; | |
export function map<T extends TObject, U>( | |
collection: T, | |
map: Mapper<T, U> | |
): Record<keyof T, U>; | |
export function map<T extends Mapable, U>( | |
collection: Mapable, | |
map: Mapper<T, U> | |
) { | |
if (Array.isArray(collection)) { | |
return collection.map(map as Mapper<TArray, U>); | |
} | |
return Object.fromEntries( | |
Object.entries(collection).map(([key, value]) => [ | |
key, | |
(map as Mapper<TObject, U>)(value, key, collection), | |
]) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment