Skip to content

Commit

Permalink
fix: 调整pow函数实现逻辑,增加测试用例
Browse files Browse the repository at this point in the history
  • Loading branch information
F-jianchao authored and CheshireJCat committed Oct 12, 2024
1 parent f6d8964 commit 4f7c444
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
6 changes: 6 additions & 0 deletions packages/amis-formula/__tests__/async-fomula.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
Expand Down
20 changes: 13 additions & 7 deletions packages/amis-formula/src/evalutor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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}) {
Expand Down Expand Up @@ -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;
}

Expand Down

0 comments on commit 4f7c444

Please sign in to comment.