JavaScript 表达式评价器
说明
解析并评价数学表达式. 越来越安全了
使用 JavaScript 的数学取而代之 eval 数学函数
表达.
它为常见的数学操作员和函数提供了内在支持. 此外, 您可以添加自己的 JavaScript 函数。 可评价表达式 直接,或编译为本地JavaScript函数.
安装
npm install expr-eval
基本用途
const Parser = require('expr-eval').Parser;
const parser = new Parser();
let expr = parser.parse('2 * x + 1');
console.log(expr.evaluate({ x: 3 })); // 7
// or
Parser.evaluate('6 * x', { x: 7 }) // 42
文档
解析器
帕塞尔是图书馆的主要班级. 它有如单一 parse 方法,以及
分析和评价表达式的"静态"方法.
解析器 ()
构造一个新的 Parser 举个例子.
构造器选择一个 options 参数允许您启用或禁用运算符.
例如,以下将创建一个 Parser 不允许比较或逻辑运算符,但确实允许 in数字 :
const parser = new Parser({
operators: {
// These default to true, but are included to be explicit
add: true,
concatenate: true,
conditional: true,
divide: true,
factorial: true,
multiply: true,
power: true,
remainder: true,
subtract: true,
// Disable and, or, not, <, ==, !=, etc.
logical: false,
comparison: false,
// Disable 'in' and = operators
'in': false,
assignment: false
}
});
剖析( 表达式: 字符串)
将数学表达式转换为 Expression 对象.
Parse( 表达式: 字符串)
静态等同 new Parser().parse(expression)。 。 。 .
Parser. value( 表达式: 字符串, 变量? : 对象)
分析并立即评估使用值和函数的表达式
页:1 variables 对象.
Parser. ergor (expr, vars) 相当于呼叫 Parser.parse (expr). vals (vars) (英语).
表达式
Parser.parse(str) 返回一个 Expression 对象. Expressions 类似于
JavaScript 函数,即它们可以“称为”变量,并绑定到
输入值。 事实上,它们甚至可以被转换成JavaScript
函数.
值( 可变值) : 对象
评估表达式, 变量绑定在 {可变值} 中 。 每个
变量在表达式中绑定在
variables 对象。 如果有无约束变量, evaluate 将扔出一个
除外.
js> expr = Parser.parse("2 ^ x");
(2^x)
js> expr.evaluate({ x: 3 });
8
替代( 可变: 字符串, 表达式: 表达式 QQ 字符串 QQ 数字)
创建新 Expression 将指定的变量替换为另一个变量
表达式。 这类似于函数构成. 若为 expression 是一个字符串
或数字,将解为 Expression。 。 。 .
js> expr = Parser.parse("2 * x + 1");
((2*x)+1)
js> expr.substitute("x", "4 * x");
((2*(4*x))+1)
js> expr2.evaluate({ x: 3 });
25
简化( 可变: 对象)
简化常数子表达式,并用文字取代可变引用 数值。 这基本上是一种局部评价,它同样有助于 以所提供的变量进行计算。 函数调用不是 评估(内置操作员的功能除外),因为可能不是 决断相.
简化很简单 例如,它不知道增加和
乘相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相相 ((2*(4*x))+1) 从上一个例子
除非您提供了 x 的值,否则无法简化. 2*4*x+1 不过,
因为它被解释为 (((2*4)*x)+1),所以请 (2*4) 子表达式将会是
改为“8”,导致 ((8*x)+1)。 。 。 .
js> expr = Parser.parse("x * (y * atan(1))").simplify({ y: 4 });
(x*3.141592653589793)
js> expr.evaluate({ x: 2 });
6.283185307179586
变量( 选项 ? : 对象)
在表达式中获取一组未绑定变量.
js> expr = Parser.parse("x * (y * atan(1))");
(x*(y*atan(1)))
js> expr.variables();
x,y
js> expr.simplify({ y: 4 }).variables();
x
默认, variables 将返回“顶级”对象,例如, Parser.parse(x.y.z).variables() 返回时 ['x']。如果想要获得整个对象成员链,可以使用 { withMembers: true }。 。 Parser.parse(x.y.z).variables({ withMembers: true }) 将返回 ['x.y.z']。 。 。 .
符号( 选项 ? ): 对象)
获取一系列变量,包括用于 表达式.
js> expr = Parser.parse("min(x, y, z)");
(min(x, y, z))
js> expr.symbols();
min,x,y,z
js> expr.simplify({ y: 4, z: 5 }).symbols();
min,x
喜欢 variables, (中文(简体) ), symbols 接受选项参数 { withMembers: true } 包括对象成员.
转到 String ()
将表达式转换为字符串. toString() 环绕每个子表达式
带有括号(文字值、变量和函数调用除外),因此
用于调试优先级错误 .
到JSFunction( 参数: 阵列QQ字符串, 变量? : 对象)
转换一个 Expression 对象进入可调用的 JavaScript 函数. parameters
是一系列参数名称,或字符串,名称用逗号分隔.
如果可选 variables 参数,表达式为
与提供的数值相绑定的变量简化.
js> expr = Parser.parse("x + y + z");
((x + y) + z)
js> f = expr.toJSFunction("x,y,z");
[Function] // function (x, y, z) { return x + y + z; };
js> f(1, 2, 3)
6
js> f = expr.toJSFunction("y,z", { x: 100 });
[Function] // function (y, z) { return 100 + y + z; };
js> f(2, 3)
105
表达式语法
解析器接受一个相当基本的语法. 它与普通JavaScript类似
表达式,但更注重数学. 例如 ^ 运算符是
推而论之,非克也.
运算符优先
| 运算符 | 协会 | 说明 |
|---|---|---|
| (...) | 无 | 分组 |
| f(), x.y, a[一] | 左边 | 函数调用、属性访问、阵列索引 |
| 来啊! | 左边 | 阶乘 |
| ^ | 对 | 指标 |
| +,-, 不, sqrt等 . | 对 | 统一前缀运算符(完整列表见下文) |
| *, /,% (单位:千美元) | 左边 | 乘法,除法,剩余部分 |
| +, -, || | 左边 | 加、减、数组/列表连接 |
| ==, !; >=; <=; <; <; <; <; > | 左边 | 等号,不等号等号等号,"入"指"左行"是否包含在右行数组行" |
| 财务报告和审定财务报表 | 左边 | 逻辑和 |
| 或者说 | 左边 | 逻辑 OR |
| * * y:z * 翻译: | 对 | 第三级条件(如果 x 然后 y else z) |
| =: | 对 | 可变任务 |
| · ; | 左边 | 表达式分隔符 |
| ```(```) |
const parser = new Parser({
operators: {
'in': true,
'assignment': true
}
});
// Now parser supports 'x in array' and 'y = 2*x' expressions
#### Unary operators
The parser has several built-in "functions" that are actually unary operators.
The primary difference between these and functions are that they can only accept
exactly one argument, and parentheses are optional. With parentheses, they have
the same precedence as function calls, but without parentheses, they keep their
normal precedence (just below `^`). For example, `sin(x)^2` is equivalent to
`(sin x)^2`, and `sin x^2` is equivalent to `sin(x^2)`.
The unary `+` and `-` operators are an exception, and always have their normal
precedence.
Operator | Description
:------- | :----------
-x | Negation
+x | Unary plus. This converts it's operand to a number, but has no other effect.
x! | Factorial (x * (x-1) * (x-2) * … * 2 * 1). gamma(x + 1) for non-integers.
abs x | Absolute value (magnitude) of x
acos x | Arc cosine of x (in radians)
acosh x | Hyperbolic arc cosine of x (in radians)
asin x | Arc sine of x (in radians)
asinh x | Hyperbolic arc sine of x (in radians)
atan x | Arc tangent of x (in radians)
atanh x | Hyperbolic arc tangent of x (in radians)
cbrt x | Cube root of x
ceil x | Ceiling of x — the smallest integer that’s >= x
cos x | Cosine of x (x is in radians)
cosh x | Hyperbolic cosine of x (x is in radians)
exp x | e^x (exponential/antilogarithm function with base e)
expm1 x | e^x - 1
floor x | Floor of x — the largest integer that’s <= x
length x | String or array length of x
ln x | Natural logarithm of x
log x | Natural logarithm of x (synonym for ln, not base-10)
log10 x | Base-10 logarithm of x
log2 x | Base-2 logarithm of x
log1p x | Natural logarithm of (1 + x)
not x | Logical NOT operator
round x | X, rounded to the nearest integer, using "grade-school rounding"
sign x | Sign of x (-1, 0, or 1 for negative, zero, or positive respectively)
sin x | Sine of x (x is in radians)
sinh x | Hyperbolic sine of x (x is in radians)
sqrt x | Square root of x. Result is NaN (Not a Number) if x is negative.
tan x | Tangent of x (x is in radians)
tanh x | Hyperbolic tangent of x (x is in radians)
trunc x | Integral part of a X, looks like floor(x) unless for negative number
#### Pre-defined functions
Besides the "operator" functions, there are several pre-defined functions. You
can provide your own, by binding variables to normal JavaScript functions.
These are not evaluated by simplify.
Function | Description
:------------ | :----------
random(n) | Get a random number in the range [0, n). If n is zero, or not provided, it defaults to 1.
fac(n) | n! (factorial of n: "n * (n-1) * (n-2) * … * 2 * 1") Deprecated. Use the ! operator instead.
min(a,b,…) | Get the smallest (minimum) number in the list.
max(a,b,…) | Get the largest (maximum) number in the list.
hypot(a,b) | Hypotenuse, i.e. the square root of the sum of squares of its arguments.
pyt(a, b) | Alias for hypot.
pow(x, y) | Equivalent to x^y. For consistency with JavaScript's Math object.
atan2(y, x) | Arc tangent of x/y. i.e. the angle between (0, 0) and (x, y) in radians.
roundTo(x, n) | Rounds x to n places after the decimal point.
map(f, a) | Array map: Pass each element of `a` the function `f`, and return an array of the results.
fold(f, y, a) | Array fold: Fold/reduce array `a` into a single value, `y` by setting `y = f(y, x, index)` for each element `x` of the array.
filter(f, a) | Array filter: Return an array containing only the values from `a` where `f(x, index)` is `true`.
indexOf(x, a) | Return the first index of string or array `a` matching the value `x`, or `-1` if not found.
join(sep, a) | Concatenate the elements of `a`, separated by `sep`.
if(c, a, b) | Function form of c ? a : b. Note: This always evaluates both `a` and `b`, regardless of whether `c` is `true` or not. Use `c ? a : b` instead if there are side effects, or if evaluating the branches could be expensive.
#### Array literals
Arrays can be created by including the elements inside square `[]` brackets, separated by commas. For example:
[ 1, 2, 3, 2+2, 10/2, 3! ]
#### Function definitions
You can define functions using the syntax `name(params) = expression`. When it's evaluated, the name will be added to the passed in scope as a function. You can call it later in the expression, or make it available to other expressions by re-using the same scope object. Functions can support multiple parameters, separated by commas.
Examples:
```js
square(x) = x*x
add(a, b) = a + b
factorial(x) = x < 2 ? 1 : x * factorial(x - 1)
自定义 JavaScript 函数
如果您需要额外的功能而不支持在框外,您可以轻松地在自己的代码中添加这些功能. 联合国 Parser 类有一个财产叫 functions 只是一个具有所有范围功能的物体。 您可以添加,替换,或删除任何属性来自定义表达式中的可用内容. 例如:
const parser = new Parser();
// Add a new function
parser.functions.customAddFunction = function (arg1, arg2) {
return arg1 + arg2;
};
// Remove the factorial function
delete parser.functions.fac;
parser.evaluate('customAddFunction(2, 4) == 6'); // true
//parser.evaluate('fac(3)'); // This will fail
常数
解析器还包括一些可以用于表达式的预定义常数. 这些显示 见下表:
| 常数 | 说明 |
|---|---|
| 页:1 | 价值 Math.E 从您的 JavaScript 运行时间 |
| 个人信息 | 价值 Math.PI 从您的 JavaScript 运行时间 |
| 真实 | 逻辑 true 价值 |
| 虚假 | 逻辑 false 价值 |
预定义常数存储于 parser.consts您可以修改此属性以自定义
用于表达式的常数。 例如:
const parser = new Parser();
parser.consts.R = 1.234;
console.log(parser.parse('A+B/R').toString()); // ((A + B) / 1.234)
要禁用预定义的常数, 您可以替换或删除 parser.consts数字 :
const parser = new Parser();
parser.consts = {};
测试
cd到项目目录- 安装开发依赖性 :
npm install - 运行测试 :
npm test