General Expression Parser
安装
npm install --save gep
或
bower install --save gep
使用
快速上手
const gep = const fun = gepconst result = console// true
使用参数
const gep = params: '$' 'SQUARE_METER' const scope = radius: 3 { return n * n } { return numObj }const SQUARE_METER = 'm²' const source = 'fixed((Math.PI + square(radius)), 2) + SQUARE_METER'const result = gepscope SQUARE_METER console// 12.14m²
API
参数
const gep = cache: 1000 scope: '$' params: '$' 'other_param'
cache: Number
类型,gep 内部使用 LRU 缓存解析过的表达式,cache
表示最大缓存数,默认 1000
scope: String
类型,已解析的表达式或函数中,用于表示 scope
的变量名,默认 '$'
const gep = const parsed = gepconsole// $.a+$.b
params: Array
类型,该数组中每一项都为 String
类型,执行函数时需要依次传入对应的参数。
第一个必须为 scope
对应的变量名。其余变量名,在表达式中可以直接被访问。
const gep = params: '$' 'other'const scope = a: 1const other = a: 2const result = gepscope otherconsole// 3
方法
parse: 参数为 String
类型的待编译的表达式,返回编译好的 String
类型表达式
const gep = const source = 'a + b'const expression = gepconsole// $.a+$.b
build: 参数为 String
类型的已编译表达式,返回编译好的 Function
(成功) 或 undefined
(失败)
const gep = const source = 'a + b'const expression = gep // $.a+$.bconst fun = gep // 返回函数,类似 function($){return $.a+$.b}const result = console// 3
buildToString: 和 build 类似,参数为 String
类型的已编译表达式,返回的是函数字符串
const gep = const expression = gep // $.a+$.bconst funString = gepconsole// function($){return $.a+$.b}
make: 和 build 类似,参数为 String
类型的待编译表达式,返回编译好的 Function
(成功) 或 undefined
(失败)
const gep = const source = 'a + b'const fun = gep // 返回函数,类似 function($){return $.a+$.b}const result = console// 3
makeToString: 和 make 类似,参数为 String
类型的待编译表达式,返回的是函数字符串
const gep = const funString = gepconsole// function($){return $.a+$.b}