Skip to content

Instantly share code, notes, and snippets.

@haggen
Last active March 4, 2023 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haggen/6a5f1bbb60828695e85af0f94821e8a5 to your computer and use it in GitHub Desktop.
Save haggen/6a5f1bbb60828695e85af0f94821e8a5 to your computer and use it in GitHub Desktop.
Map function in TypeScript that works for Arrays as well as Objects.
/**
* 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