ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...

    Function firstMap

    • 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.

      Type Parameters

      • T
      • R

      Parameters

      • fn: (arg: T) => void | R

        The function to apply to each value

      • properties: T[]

        Array of values to try the function on

      Returns void | R

      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;
      // }
      }