Skip to content

Instantly share code, notes, and snippets.

@SugarDarius
Last active October 20, 2022 07:26
Show Gist options
  • Save SugarDarius/7d29bf51d9bb4447059185d01bd6f78a to your computer and use it in GitHub Desktop.
Save SugarDarius/7d29bf51d9bb4447059185d01bd6f78a to your computer and use it in GitHub Desktop.
TypeScript recursive map
/*
* mapRecursive
* author: Aurélien Dupays Dexemple
*/
export const isUndefined = (obj: any): obj is undefined => typeof obj === 'undefined';
export function mapRecursive<TInput, TOutput>(fn: (e: TInput, index?: number) => TOutput, [first, ...rest]: TInput[], index: number = 0): TOutput[] {
return isUndefined(first) ? [] : [fn(first, index), ...mapRecursive(fn, rest, ++index)];
};
@mcaple
Copy link

mcaple commented Oct 20, 2022

Hi SugarDarius,
would you mind giving an example of using this function. On first look I can get the children of first but am struggling a little to get the rest?

Merci

@SugarDarius
Copy link
Author

Hi @mcaple.
A relevant example of using this function is mapping on a tree data structure with a lower complexity.

KR,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment