ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...
    • Type guard to validate a CAS (Chemical Abstracts Service) number. CAS numbers follow a specific format (XXXXXXX-XX-X) and include a checksum digit.

      Parameters

      • cas: unknown

        The CAS number to validate

      Returns cas is `${string}-${string}-${string}`

      Type predicate indicating if the value is a valid CAS number

      isCAS('1234-56-6') // Returns true
      isCAS('50-00-0') // Returns true
      isCAS('1234-56-999') // Returns false
      export function isCAS(cas: unknown): cas is CAS<string> {
      if (typeof cas !== "string") return false;
      const regex = RegExp(`^${CAS_REGEX.source}$`);
      const match = cas.match(regex);
      if (!match || !match.groups?.seg_a || !match.groups?.seg_b || !match.groups?.seg_checksum)
      return false;

      const segA = match.groups.seg_a;
      const segB = match.groups.seg_b;
      const segChecksum = match.groups.seg_checksum;

      if (parseInt(segA) === 0 && parseInt(segB) === 0) return false;

      const segABCalc = Array.from(segA + segB)
      .map(Number)
      .reverse()
      .reduce((acc, curr, idx) => acc + (idx + 1) * curr, 0);

      return segABCalc % 10 === Number(segChecksum);
      }