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"])
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.