fix: 调整pow函数实现逻辑,增加测试用例

This commit is contained in:
fujianchao 2024-10-12 11:18:55 +08:00 committed by lmaomaoz
parent f6d8964a61
commit 4f7c444397
2 changed files with 19 additions and 7 deletions

View File

@ -139,11 +139,17 @@ test('formula:math', async () => {
expect(await evalFormual('UPPERMONEY(7682.01)')).toBe('柒仟陆佰捌拾贰元壹分');
expect(await evalFormual('UPPERMONEY(7682)')).toBe('柒仟陆佰捌拾贰元整');
expect(await evalFormual('POW(2,3)')).toBe(8);
expect(await evalFormual('POW(4,2)')).toBe(16);
// 非数字类型转换是否正常?
expect(await evalFormual('"3" + "3"')).toBe(6);
expect(await evalFormual('"3" - "3"')).toBe(0);
expect(await evalFormual('AVG(4, "6", "10", 10, 10)')).toBe(8);
expect(await evalFormual('MAX(4, "6", "10", 2, 3)')).toBe(10);
expect(await evalFormual('POW("2","3")')).toBe(8);
expect(await evalFormual('POW("22.3",2)')).toBe(497.29);
expect(await evalFormual('POW("word2",2)')).toBe('word2');
expect(await evalFormual('"a" + "b"')).toBe('ab');
});

View File

@ -13,8 +13,6 @@ import uniqBy from 'lodash/uniqBy';
import isEqual from 'lodash/isEqual';
import isPlainObject from 'lodash/isPlainObject';
import get from 'lodash/get';
import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import {EvaluatorOptions, FilterContext, FilterMap, FunctionMap} from './types';
import {FormulaEvalError} from './error';
@ -218,10 +216,21 @@ export class Evaluator {
return value ?? 0;
}
// 判断是否是数字或者字符串数字
isValidValue(value: string | number) {
return (
typeof value === 'number' ||
(typeof value === 'string' && /^\d+(\.\d+)?$/.test(value as string))
);
}
power(ast: {left: any; right: any}) {
const left = this.evalute(ast.left);
const right = this.evalute(ast.right);
return Math.pow(this.formatNumber(left), this.formatNumber(right));
if (!this.isValidValue(left) || !this.isValidValue(right)) {
return left;
}
return Math.pow(left, right);
}
multiply(ast: {left: any; right: any}) {
@ -1044,10 +1053,7 @@ export class Evaluator {
* @returns {number}
*/
fnPOW(base: number, exponent: number) {
const isValidValue = (value: string | number) => {
return isNumber(value) || (isString(value) && /^[0-9]+$/.test(value));
};
if (!isValidValue(base) || !isValidValue(exponent)) {
if (!this.isValidValue(base) || !this.isValidValue(exponent)) {
return base;
}