Created
February 27, 2024 21:25
-
-
Save luisvinicius09/b9c15f23c16e75fb8dd8a60fedee7cc3 to your computer and use it in GitHub Desktop.
ForEach, Filter, Map using reduce in TS
This file contains hidden or 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
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