Math Evaluator — TypeScript source
Evaluate math expressions - arithmetic, functions (sqrt, sin, log), comparisons, and constants (pi, e) - safely, in real time. Input is constrained to math-safe characters, fully client-side.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Safe math expression evaluator backed by `mathjs`. mathjs's `evaluate` is an
// evaluator, NOT a sandbox, so input is constrained to a strict math-character
// allowlist (blocks code-injection vectors, e.g. via a shared-link expression).
// The unit-test surface for the Math Evaluator tool.
import { evaluate } from 'mathjs';
const SAFE_CHARS = /^[0-9+\-*/().,\s a-zA-Z%^!<>]+$/;
const FORBIDDEN = /\b(import|require|eval|function|while|for|process|global|this|window|document|constructor)\b/;
const MAX_LEN = 200;
/** Evaluate a math expression to a display string, or null if unsafe/invalid. */
export function evaluateExpression(expr: string): string | null {
const trimmed = expr.trim();
if (trimmed === '' || trimmed.length > MAX_LEN) return null;
if (!SAFE_CHARS.test(trimmed) || FORBIDDEN.test(trimmed)) return null;
try {
const result = evaluate(trimmed);
if (typeof result === 'function') return null;
// String literals can't occur (the allowlist blocks quotes), so every
// remaining result (number, boolean, Complex, Unit, …) formats via String.
return String(result);
} catch {
return null;
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →