Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Text · 19 lines · 878 B · at 503e839

import { Ok, Err, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type AmountError = { kind: "invalid_amount"; input: string } | { kind: "too_large" };const GRAMMAR = /^(-?)(0|[1-9]\d*|[1-9]\d{0,2}(?:,\d{3})+)(?:\.(\d{1,2}))?$/;const toCents = (sign: string, whole: string, frac: string): Result<number, AmountError> => {  const cents = BigInt(whole.replace(/,/g, "") + frac.padEnd(2, "0"));  const n = Number(cents);  return cents > BigInt(Number.MAX_SAFE_INTEGER) ? Err({ kind: "too_large" }) : Ok(sign === "-" && n !== 0 ? -n : n);};/** Returns integer cents. */export const parseAmount = (text: string): Result<number, AmountError> =>  match (fromNullable(GRAMMAR.exec(text))) {    Some(m) => toCents(m[1], m[2], fromNullable(m[3]).unwrapOr("")),    None => Err({ kind: "invalid_amount", input: text }),  };