Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 23 lines · 913 B · at 74947de

export type AmountFailure = { kind: "invalid_amount"; input: string } | { kind: "too_large" };export class AmountError extends Error {  declare readonly kind: AmountFailure["kind"];  declare readonly input?: string;  constructor(failure: AmountFailure) {    super(failure.kind);    Object.assign(this, failure);  }}const GRAMMAR = /^(-?)(0|[1-9]\d*|[1-9]\d{0,2}(?:,\d{3})+)(?:\.(\d{1,2}))?$/;/** Returns integer cents. Throws AmountError on malformed or oversized input. */export function parseAmount(text: string): number {  const m = GRAMMAR.exec(text);  if (!m) throw new AmountError({ kind: "invalid_amount", input: text });  const digits = m[2].replace(/,/g, "") + (m[3] ?? "").padEnd(2, "0");  const cents = BigInt(digits);  if (cents > BigInt(Number.MAX_SAFE_INTEGER)) throw new AmountError({ kind: "too_large" });  const n = Number(cents);  return m[1] === "-" && n !== 0 ? -n : n;}