Created
June 25, 2023 20:28
-
-
Save D1360-64RC14/b0feb442d293871f3fae1eff8debd887 to your computer and use it in GitHub Desktop.
Remap: a way of doing filter and map at the same time.
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
// remap gets the array you want to process and the callback function, passing to it the same properties as a map. | |
// The data returned by the callbackFn will be filtered out if undefined, or mapped in if something else. | |
// Everything at the cost of only one loop pass. | |
function remap<T, R>(array: T[], callbackFn: (value: T, index: number, array: T[]) => R | undefined): R[] { | |
const result = new Array<R>(); | |
for (let i = 0; i < array.length; i++) { | |
const data = callbackFn(array[i], i, array); | |
if (data !== undefined) result.push(data); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment