# @adifkz/exp-p 中文文档

规范地址：https://npmcn.com/package/%40adifkz/exp-p/

版本：2\.0\.0
npm 元数据更新时间：2026-02-13T01:10:35.728Z
中文译文更新时间：2026-11-07T02:13:44.576Z
软件包许可：ISC

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40adifkz/exp-p
原文对照：https://npmcn.com/package/%40adifkz/exp-p/?lang=original
项目主页：https://github.com/adyfk/exp-p#readme
源码仓库：https://github.com/adyfk/exp-p

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：47 kB，9 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2023-06-10T17:37:45.591Z
- 最新版本发布：2026-02-13T01:10:35.588Z
- 近 30 天下载量：2073（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：34（近 12 个月 1 个）

## 中文简介

表达式解析器

## 安装

```sh
npm install @adifkz/exp-p
```

也可以使用：`pnpm add @adifkz/exp-p`、`yarn add @adifkz/exp-p`、`bun add @adifkz/exp-p`

## README

# JavaScript/ TypeScript 的表达式解析器

[![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://npmcn.com/package/%40adifkz/exp-p/LICENSE)

表达式Parser库又名"@adifkz/exp-p",是解析和评价数学和逻辑表达式的有力工具. 它为将表达解析能力融入您的项目提供了一个灵活而可扩展的解决方案. 此文档将引导您使用、 定制选项和 API 。 您可以在 npm 上找到“ @ adifkz/ exp- p” 软件包名下的库和 GitHub 上的源代码 [https://github.com/adyfk/exp-p 页面存档备份,存于互联网档案馆](https://github.com/adyfk/exp-p)。 。 。 .

## 特征

-   使用运算符评估数学表达式 `+`, (中文(简体) ), `-`, (中文(简体) ), `*`, (中文(简体) ), `/`, (中文(简体) ), `%`, (中文(简体) ), `^`等 (中文(简体) ).
-   使用运算符评估逻辑表达式 `AND`, (中文(简体) ), `OR`, (中文(简体) ), `NOT`等 (中文(简体) ).
-   支持括号来控制操作顺序.
-   在表达式中定义和使用变量.
-   定义自定义函数以扩展解析器的功能.
-   评估字符串字元.
-   评估数组字元并在数组上执行操作.
-   动态评估对象字面和访问属性 .

## 安装

您可以使用 npm 安装表达式Parser :

```bash
npm install @adifkz/exp-p
```

## 使用量

要在 JavaScript 代码中使用表达式Parser, 您需要导入表达式Parser 类并创建实例 :

```typescript
import { createParser } from '@adifkz/exp-p';

const parser = createParser();
```

## 评价表达式

一旦您创建了表达式Parser实例,您就可以使用评价方法来评价表达式. 评估方法需要两个参数:用于评价的表达和包含表达中使用的变量和函数的可选上下文对象.

```typescript
const parser = createParser();

const result = parser.evaluate('2 + 3 * 4'); // 14
```

## 变量映射

您可以定义变量,并在表达式中使用变量,为评价方法提供上下文对象.

```typescript
const parser = createParser();

// Define variables
const variables = {
  x: 5,
  y: 10,
};

// Evaluate expression with variables
const result = parser.evaluate("x + y", variables);
console.log(result); // Output: 15
```

## 函数扩展

表达式解析器允许您通过添加自定义函数来扩展其功能. 以下是定义自定义函数的例子:

```typescript
const parser = createParser();

// Define custom function
const functions = {
  square: (_, value: number) => value * value,
};

parser.setFunctions(functions)
// Evaluate expression with custom function
const result = parser.evaluate("square(5)");
console.log(result); // Output: 25
```

## 实例

```typescript
import moment from 'moment'
import { createParser, FunctionMap } from '../'

describe('example', () => {
  it('basic operator', () => {
    const parser = createParser({
    })
    expect(parser.evaluate('(2 + 3) * 4 - 4')).toBe(16)
    expect(parser.evaluate('-4 + 5')).toBe(1)
    expect(parser.evaluate('4 <= (5 + 2)')).toBe(true)
    expect(parser.evaluate('4 > 5')).toBe(false)
    expect(parser.evaluate('5 ^ 2 + 2')).toBe(27)
    expect(parser.evaluate('5 + 4 * 4')).toBe(21)
    expect(parser.evaluate('5 % 3')).toBe(2)
    expect(parser.evaluate('5.5 * 3')).toBe(16.5)
    expect(parser.evaluate('5 == 5')).toBe(true)
  });
  it('function', () => {
    // Usage example
    const variables = { x: 5 };
    const functions: FunctionMap = {
      add: (_, a: number, b: number) => a + b,
      length: (_, str: string) => str.length,
      length_all: (_, str1: string, str2: string, str3: string) => [str1.length, str2.length, str3.length],
    };
    const parser = createParser({ variables });
    parser.setFunctions(functions)
    expect(parser.evaluate('add(1 + 1, 5) + x')).toBe(12)
    expect(parser.evaluate('length("ADI") + 5', variables)).toBe(8)
    expect(parser.evaluate('length_all("ADI", "FA", "TK")', variables)).toEqual([3, 2, 2])
  });
  it('string', () => {
    const parser = createParser();
    expect(parser.evaluate('"ADI"')).toBe("ADI")
    expect(parser.evaluate('\'ADI\'')).toBe("ADI")
    expect(parser.evaluate('regex("ddd212sdf","\\d\\w\\d")')).toBe(true)
    expect(parser.evaluate('regex("ddd212sdf","\\d\\w\\d","y")')).toBe(false)
  })
  it('boolean', () => {
    const parser = createParser();
    expect(parser.evaluate('true and false')).toBe(false)
    expect(parser.evaluate('true or false')).toBe(true)
    expect(parser.evaluate('!true')).toBe(false)
    expect(parser.evaluate('!!true')).toBe(true)
  })
  it('array', () => {
    const parser = createParser();
    expect(parser.evaluate("[1, 2, 3, 4]")).toEqual([1, 2, 3, 4])
    expect(parser.evaluate("[\"2\", 5]")).toEqual(["2", 5])
    expect(parser.evaluate("[2 + 5, 5]")).toEqual([7, 5])
    expect(parser.evaluate("[5, x]", { x: 2 })).toEqual([5, 2])
  })
  it('array method', () => {
    const parser = createParser();
    const products = [
      { name: 'Product 1', price: 150, quantity: 2 },
      { name: 'Product 2', price: 80, quantity: 0 },
      { name: 'Product 3', price: 200, quantity: 5 },
      { name: 'Product 4', price: 120, quantity: 1 }
    ];
    expect(
      parser.evaluate('filter(products, "_item_.price > 100 and _item_.quantity > 0")', {
        products
      })
    ).toEqual([
      { name: 'Product 1', price: 150, quantity: 2 },
      { name: 'Product 3', price: 200, quantity: 5 },
      { name: 'Product 4', price: 120, quantity: 1 }
    ])

    expect(
      parser.evaluate('map(products, "_item_.name")', {
        products
      })
    ).toEqual([
      'Product 1',
      'Product 2',
      'Product 3',
      'Product 4',
    ])

    expect(
      parser.evaluate('find(products, "_item_.price > 0")', {
        products
      })
    ).toEqual({
      "name": "Product 1",
      "price": 150,
      "quantity": 2
    })

    expect(
      parser.evaluate('some(products, "_item_.price == 200")', {
        products
      })
    ).toBe(true)

    expect(
      parser.evaluate('reduce(products, "_curr_ + _item_.price", 0)', {
        products
      })
    ).toBe(550)
  })
  it('object', () => {
    const parser = createParser();
    expect(parser.evaluate("{ name: 'ADI', age: 20 }")).toEqual({
      name: "ADI",
      age: 20
    })
    expect(parser.evaluate("{ name: 'ADI', age: 5 + 2 }")).toEqual({
      name: "ADI",
      age: 7
    })
    expect(parser.evaluate("object.name", { object: { name: 'ADI' } })).toEqual('ADI')
    expect(parser.evaluate("object.name", { object: { name: 'ADI' } })).toEqual('ADI')
    expect(parser.evaluate("object.0.name", { object: [{ name: 'ADI' }] })).toEqual('ADI')
    expect(parser.evaluate("object.0.object.0.name", { object: [{ name: 'ADI', object: [{ name: "ADI" }] }] })).toEqual('ADI')
  })
  it('date', () => {
    const parser = createParser();

    // expect(parser.evaluate(`date()`)).toBe(moment().toISOString())
    expect(parser.evaluate(`date("2020-01-01")`)).toBe('2019-12-31T17:00:00.000Z')
    expect(parser.evaluate(`date_day(date("2020-01-01"))`)).toBe(1)
    expect(parser.evaluate(`date_month(date("2020-01-01"))`)).toBe(1)
    expect(parser.evaluate(`date_year(date("2020-01-01"))`)).toBe(2020)
    expect(parser.evaluate(`date_format("DD-MM-YYYY", "2020-01-01")`)).toBe("01-01-2020")
    expect(parser.evaluate(`date_in_format("YYYY-MM-DD", "2020-01-01")`)).toBe('2019-12-31T17:00:00.000Z')
    expect(parser.evaluate(`date_in_millis(${moment("2020/01/01", 'YYYY/MM/DD').valueOf()})`)).toBe('2019-12-31T17:00:00.000Z')
    expect(parser.evaluate(`date_millis("2020-01-01")`)).toBe(1577811600000)
    expect(parser.evaluate(`date_format("DD-MM-YYYY", date_plus(1, "day", "2020-01-05"))`)).toBe("06-01-2020")
    expect(parser.evaluate(`date_format("DD-MM-YYYY", date_plus(-1, "day", "2020-01-05"))`)).toBe("04-01-2020")
    expect(parser.evaluate(`date_format("DD-MM-YYYY", date_minus(1, "day", "2020-01-05"))`)).toBe("04-01-2020")
    expect(parser.evaluate(`date_format("DD-MM-YYYY", date_minus(-1, "day", "2020-01-05"))`)).toBe("06-01-2020")
  })
});
```

## 常见问题

### @adifkz/exp-p 是什么？

表达式解析器

### 如何安装 @adifkz/exp-p？

在项目目录运行 npm install @adifkz/exp-p，或使用 pnpm add / yarn add / bun add。

### @adifkz/exp-p 支持 TypeScript 吗？

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

### @adifkz/exp-p 支持 ESM 还是 CommonJS？

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

### @adifkz/exp-p 可以商用吗？

@adifkz/exp-p 使用 ISC 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @adifkz/exp-p 的下载量有多少？

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

### @adifkz/exp-p 还在维护吗？

最新版本 2\.0\.0 发布于 2026/02/13（8 个月前）；至今共发布 34 个版本，其中过去 12 个月发布了 1 个；首次发布于 2023/06/11。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

