Skip to content

Instantly share code, notes, and snippets.

@D1360-64RC14
Created June 25, 2023 20:28
Show Gist options
  • Save D1360-64RC14/b0feb442d293871f3fae1eff8debd887 to your computer and use it in GitHub Desktop.
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.
// 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