https://github.com/papirosko/expressions-parser
https://github.com/papirosko/expressions-parser
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/papirosko/expressions-parser
- Owner: papirosko
- License: mit
- Created: 2022-11-23T15:52:42.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-03-21T13:21:16.000Z (over 3 years ago)
- Last Synced: 2025-03-10T11:02:39.076Z (over 1 year ago)
- Language: TypeScript
- Size: 144 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# expressions-parser
`expressions-parser` allows you to parse expression from string and evaluate it.
Install:
```
npm i expressions-parser
```
How to use:
```typescript
import {toAST, parseInput, apply} from 'expressions-parser';
const ast = toAST(parseInput('1 + 1'));
apply(ast, {}); // return 2
```
# Expressions syntax
Allowed are:
* numbers: `1`, `100500`, `-1`
* strings (both single and double quoted): `'test string'`, `"another string"`
* boolean: `false`, `true`
* object field access: `obj.field`
* indexed access: `field[0]`, `field['property']`, `field[propVariable]`
* method call: `obj.method()`, `obj.method(arg1, 'arg2', 0)`
## Pipes
You can use pipes the same way as in angular:
```typescript
import {toAST, parseInput, apply} from 'expressions-parser';
const ast = toAST(parseInput('obj.numbers | min:10 | sum'));
const sum = apply(ast, {
obj: {
numbers: [1, 2, 11, 19, 15]
}
}, {
pipes: {
min: (arr: number[], min: number) => arr.filter(x => x >= min),
sum: (arr: number[]) => arr.reduce((a, b) => a + b, 0)
}
}); // returns 45
```