Skip to content

Instantly share code, notes, and snippets.

@luisvinicius09
Created February 27, 2024 21:25
Show Gist options
  • Save luisvinicius09/b9c15f23c16e75fb8dd8a60fedee7cc3 to your computer and use it in GitHub Desktop.
Save luisvinicius09/b9c15f23c16e75fb8dd8a60fedee7cc3 to your computer and use it in GitHub Desktop.
ForEach, Filter, Map using reduce in TS
function myForEach<T>(
input: T[],
callback: (element: T, index: number, array: T[]) => void
): void {
return input.reduce((acc, curr, idx, arr) => {
callback(curr, idx, arr)
return undefined;
}, undefined);
}
function myFilter<T>(
input: T[],
callback: (element: T, index: number, array: T[]) => boolean
): T[] {
return input.reduce<T[]>((acc, curr, idx, arr) => callback(curr, idx, arr) ? [...acc, curr] : acc, []);
}
function myMap<T, K>(
input: T[],
callback: (element: T, index: number, array: T[]) => K
): K[] {
return input.reduce<K[]>((acc, curr, idx, arr) => [...acc, callback(curr, idx, arr)], []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment