studio / src /utils /calc.js
cheumk's picture
Upload 32 files
4e039c5 verified
Raw History Blame Contribute Delete
4.63 kB
/* ------------------------------------------------------------------ *
* 安全數學求值(無 eval / Function)。
*
* 模型輸出的 expression 屬於不可信輸入,因此只用自寫的 tokenizer +
* 遞迴下降解析器求值。支援:
* 數字、+ - * / % ^(次方)、括號、逗號
* 常數:pi, e
* 函式:sqrt abs round floor ceil exp ln log log10 log2
* sin cos tan asin acos atan min max pow
* ------------------------------------------------------------------ */
const FUNCS = {
sqrt: Math.sqrt, abs: Math.abs, round: Math.round, floor: Math.floor, ceil: Math.ceil,
exp: Math.exp, ln: Math.log, log: Math.log10, log10: Math.log10, log2: Math.log2,
sin: Math.sin, cos: Math.cos, tan: Math.tan, asin: Math.asin, acos: Math.acos, atan: Math.atan,
min: Math.min, max: Math.max, pow: Math.pow,
}
const CONSTS = { pi: Math.PI, e: Math.E }
function tokenize(src) {
const tokens = []
let i = 0
while (i < src.length) {
const c = src[i]
if (/\s/.test(c)) { i++; continue }
if (/[\d.]/.test(c)) {
let j = i
while (j < src.length && /[\d.]/.test(src[j])) j++
if (src[j] === 'e' || src[j] === 'E') {
// 科學記號 1e5 / 1e-3
let k = j + 1
if (src[k] === '+' || src[k] === '-') k++
if (/\d/.test(src[k] || '')) {
j = k
while (j < src.length && /\d/.test(src[j])) j++
}
}
const num = Number(src.slice(i, j))
if (Number.isNaN(num)) throw new Error(`數字格式錯誤:${src.slice(i, j)}`)
tokens.push({ t: 'num', v: num })
i = j
continue
}
if (/[a-zA-Z_]/.test(c)) {
let j = i
while (j < src.length && /[a-zA-Z_0-9]/.test(src[j])) j++
tokens.push({ t: 'id', v: src.slice(i, j).toLowerCase() })
i = j
continue
}
if ('+-*/%^(),'.includes(c)) { tokens.push({ t: 'op', v: c }); i++; continue }
if (c === '×') { tokens.push({ t: 'op', v: '*' }); i++; continue }
if (c === '÷') { tokens.push({ t: 'op', v: '/' }); i++; continue }
throw new Error(`不支援的字元「${c}」`)
}
return tokens
}
function evaluate(src) {
const tokens = tokenize(src)
let pos = 0
const peek = () => tokens[pos]
const isOp = (v) => peek()?.t === 'op' && peek().v === v
const take = () => tokens[pos++]
function expr() {
let left = term()
while (isOp('+') || isOp('-')) {
const op = take().v
const right = term()
left = op === '+' ? left + right : left - right
}
return left
}
function term() {
let left = unary()
while (isOp('*') || isOp('/') || isOp('%')) {
const op = take().v
const right = unary()
left = op === '*' ? left * right : op === '/' ? left / right : left % right
}
return left
}
function unary() {
if (isOp('-')) { take(); return -unary() }
if (isOp('+')) { take(); return unary() }
return power()
}
function power() {
const base = primary()
if (isOp('^')) { take(); return Math.pow(base, unary()) } // 右結合
return base
}
function primary() {
const tok = take()
if (!tok) throw new Error('表達式不完整')
if (tok.t === 'num') return tok.v
if (tok.t === 'op' && tok.v === '(') {
const v = expr()
if (!isOp(')')) throw new Error('括號不配對')
take()
return v
}
if (tok.t === 'id') {
if (tok.v in CONSTS) return CONSTS[tok.v]
const fn = FUNCS[tok.v]
if (!fn) throw new Error(`未知函式或常數:${tok.v}`)
if (!isOp('(')) throw new Error(`${tok.v} 後面需要括號`)
take()
const args = []
if (!isOp(')')) {
args.push(expr())
while (isOp(',')) { take(); args.push(expr()) }
}
if (!isOp(')')) throw new Error('函式括號不配對')
take()
return fn(...args)
}
throw new Error(`預期數字,收到「${tok.v}」`)
}
const result = expr()
if (pos !== tokens.length) throw new Error('表達式有多餘字元')
return result
}
/** 回傳計算結果字串;任何異常都轉成錯誤訊息,不丟例外。 */
export function safeCalc(expression) {
if (typeof expression !== 'string' || !expression.trim()) return '計算錯誤:表達式為空'
if (expression.length > 500) return '計算錯誤:表達式過長'
try {
const value = evaluate(expression)
if (!Number.isFinite(value)) return `計算錯誤:結果無效(${expression})`
return `${expression} = ${Math.round(value * 1e10) / 1e10}`
} catch (e) {
return `計算錯誤:${expression}(${e.message})`
}
}