Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100/** * A small, safe arithmetic evaluator for $(math …). Supports + - * / % ^, * parentheses, unary minus, constants (pi, e) and common functions. */const FUNCS: Record<string, (...a: number[]) => number> = { abs: Math.abs, round: (x, d = 0) => Math.round(x * 10 ** d) / 10 ** d, floor: Math.floor, ceil: Math.ceil, sqrt: Math.sqrt, cbrt: Math.cbrt, min: Math.min, max: Math.max, log: (x, b) => (b === undefined ? Math.log10(x) : Math.log(x) / Math.log(b)), ln: Math.log, sin: Math.sin, cos: Math.cos, tan: Math.tan, random: (a = 1, b?: number) => (b === undefined ? Math.random() * a : a + Math.random() * (b - a)),}const CONSTS: Record<string, number> = { pi: Math.PI, e: Math.E }
export function evaluateMath(expr: string): number { const tokens = expr.match(/\d+(?:\.\d+)?(?:e[+-]?\d+)?|[a-z_]+|\*\*|[-+*/%^(),]/gi) if (!tokens || tokens.join('').length !== expr.replace(/\s+/g, '').length) throw new Error('Invalid math expression.') let pos = 0 const peek = () => tokens[pos] const next = () => tokens[pos++] const expect = (t: string) => { if (next() !== t) throw new Error('Invalid math expression.') }
function primary(): number { const t = next() if (t === undefined) throw new Error('Invalid math expression.') if (t === '(') { const v = additive() expect(')') return v } if (t === '-') return -unary() if (t === '+') return unary() if (/^\d/.test(t)) return Number(t) const name = t.toLowerCase() if (name in CONSTS) return CONSTS[name] if (name in FUNCS && peek() === '(') { next() const args: number[] = [] if (peek() !== ')') { args.push(additive()) while (peek() === ',') { next() args.push(additive()) } } expect(')') return FUNCS[name](...args) } throw new Error(`Unknown name “${t}”.`) } function unary(): number { return primary() } function power(): number { const base = unary() if (peek() === '^' || peek() === '**') { next() return base ** power() } return base } function multiplicative(): number { let v = power() while (peek() === '*' || peek() === '/' || peek() === '%') { const op = next() const r = power() v = op === '*' ? v * r : op === '/' ? v / r : v % r } return v } function additive(): number { let v = multiplicative() while (peek() === '+' || peek() === '-') { const op = next() const r = multiplicative() v = op === '+' ? v + r : v - r } return v }
const result = additive() if (pos !== tokens.length) throw new Error('Invalid math expression.') if (!Number.isFinite(result)) throw new Error('The result is not a finite number.') return result}
export function formatNumber(n: number): string { return Number.isInteger(n) ? String(n) : String(Number(n.toPrecision(12)))}