diff --git a/packages/amis-formula/__tests__/async-fomula.test.ts b/packages/amis-formula/__tests__/async-fomula.test.ts index 3aa3223af..9695de7cc 100644 --- a/packages/amis-formula/__tests__/async-fomula.test.ts +++ b/packages/amis-formula/__tests__/async-fomula.test.ts @@ -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'); }); diff --git a/packages/amis-formula/src/evalutor.ts b/packages/amis-formula/src/evalutor.ts index 02fb4f00f..bf802adcd 100644 --- a/packages/amis-formula/src/evalutor.ts +++ b/packages/amis-formula/src/evalutor.ts @@ -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; }