import { toNumber } from './number'; import { ERROR_VALUE, ERROR_NAME, ERROR_DIV_ZERO } from '../error'; interface Evaluater { (...params: any[]): any; } export function evaluateByOperator(operator: string, params: any[]) { const m: Record = { '+': plus, '-': minus, '*': multiply, '/': divide, '&': ampersand, '^': power, '=': equals, '<>': notEquals, '>=': gte, '>': gt, '<=': lte, '<': lt, }; const f = m[operator]; if (!f) throw Error(ERROR_NAME); return m[operator](...params); } // + function plus(...params: (string | number)[]) { const result = params.reduce((acc: number, param) => acc + toNumber(param), 0); if (isNaN(result)) { throw Error(ERROR_VALUE); } return result; } // - function minus(...params: (string | number)[]) { const result = params .slice(1) .reduce((acc: number, param) => acc - toNumber(param), toNumber(params[0])); if (isNaN(result)) { throw Error(ERROR_VALUE); } return result; } // * function multiply(...params: (string | number)[]) { const result = params .slice(1) .reduce((acc: number, param) => acc * toNumber(param), toNumber(params[0])); if (isNaN(result)) { throw Error(ERROR_VALUE); } return result; } // / => 除法 function divide(...params: (string | number)[]) { const result = params .slice(1) .reduce((acc: Number, param) => (acc as any) / toNumber(param), toNumber(params[0])); if (result === Infinity) { throw Error(ERROR_DIV_ZERO); } if (isNaN(result)) { throw Error(ERROR_VALUE); } return result; } // ^ 乘方 function power(base: string | number, n: string | number) { const result = Math.pow(toNumber(base), toNumber(n)); if (isNaN(result)) { throw new Error(ERROR_VALUE); } return result; } // & => 连字号 function ampersand(...params: (string | number)[]) { return params.reduce((acc, value) => acc + value.toString(), ''); } // 逻辑 = function equals(p1: any, p2: any) { return p1 === p2; } // 逻辑 <> function notEquals(p1: any, p2: any) { return p1 !== p2; } // 逻辑 >= function gte(p1: any, p2: any) { return p1 >= p2; } // 逻辑> function gt(p1: any, p2: any) { return p1 > p2; } // 逻辑 <= function lte(p1: any, p2: any) { return p1 <= p2; } // 逻辑 < function lt(p1: any, p2: any) { return p1 < p2; }