@datawrapper/expr-eval

中文文档
2.0.7发布于 2023/10/25TypeScriptESM + CJS零依赖近 30 天下载 5899

数学表达式评价员

中文使用文档
文档目录8 节
  1. 说明
  2. 安装
  3. 基本用途
  4. 文档
  5. 解析器
  6. 表达式
  7. 表达式语法
  8. 测试

JavaScript 表达式评价器

npm CDNJS version Build Status

说明

解析并评价数学表达式. 越来越安全了 使用 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 = {};

测试

  1. cd 到项目目录
  2. 安装开发依赖性 : npm install
  3. 运行测试 : npm test

版本与发布记录

@datawrapper/expr-eval 共发布 13 个版本,首次发布于 2020/06/16;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.7latest2023/10/253 年前
2.0.7-02023/10/253 年前
2.0.62023/10/203 年前
2.0.6-32023/10/203 年前
2.0.6-22023/10/193 年前
2.0.6-12023/10/193 年前

关于 @datawrapper/expr-eval 的常见问题

@datawrapper/expr-eval 是什么?

数学表达式评价员

如何安装 @datawrapper/expr-eval?

在项目目录运行 npm install @datawrapper/expr-eval,或使用 pnpm add / yarn add / bun add。

@datawrapper/expr-eval 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@datawrapper/expr-eval 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@datawrapper/expr-eval 可以商用吗?

@datawrapper/expr-eval 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@datawrapper/expr-eval 的下载量有多少?

根据 npm 官方下载统计,@datawrapper/expr-eval 在 2026/10/12 – 2026/11/10 这 30 天内被下载 5,899 次,日均约 197 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@datawrapper/expr-eval 还在维护吗?

最新版本 2.0.7 发布于 2023/10/25(3 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/06/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。