The first non-undefined/null result from applying the function, or undefined if all attempts fail
// Parse number from different formats
const getNumber = (s: string) => s.match(/\d+/)?.[0];
firstMap(getNumber, ["no nums", "abc123", "def"]) // Returns "123"
// Find first valid item
const isValid = (x: number) => x > 10 ? x : undefined;
firstMap(isValid, [5, 8, 15, 20]) // Returns 15
// Complex transformations
const parseDate = (s: string) => {
const date = new Date(s);
return isNaN(date.getTime()) ? undefined : date;
};
firstMap(parseDate, ["invalid", "2023-01-01", "also invalid"])
export function firstMap<T, R>(fn: (arg: T) => R | void, properties: T[]): R | void {
//try {
for (const prop of properties) {
const result = fn(prop);
if (result !== undefined && result !== null) {
return result;
}
}
return undefined;
// } catch (error) {
// //console.error("ERROR in firstMap:", error);
// throw
// return undefined;
// }
}
Takes a function and an array of values, applies the function to each value in sequence, and returns the first non-undefined/null result. Useful for trying multiple possible inputs until finding one that produces a valid result.