Skip to content

Commit 1a836ad

Browse files
committed
feat(compile): enable short-circuit evaluation by default
1 parent a2e764f commit 1a836ad

2 files changed

Lines changed: 11 additions & 6 deletions

File tree

README.md

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,8 @@ const result = expr({ sum, x })("sum * x");
169169
- `expression` - 要编译的表达式
170170
- `variables` - 表达式中使用的所有变量映射
171171
- `options` - 编译选项(可选)
172-
- `optimize?: boolean` - 是否进行优化(默认:false)
172+
- `inline?: boolean` - 是否启用内联优化,将只被引用一次的子表达式内联到使用位置(默认:true)
173+
- `shortCircuit?: boolean` - 是否启用短路求值,为 &&, ||, ??, 和三元表达式生成控制流节点(默认:true)
173174

174175
**返回值:** CompiledData 数组
175176

@@ -183,11 +184,15 @@ const product = expr({ x, y })("x * y");
183184
const result = expr({ sum, product })("sum + product");
184185

185186
const compiled = compile(result, { x, y });
187+
// [["x", "y"], "($0+$1)", "($0*$1)", "$2+$3"]
188+
189+
// 禁用内联优化
190+
const noInline = compile(result, { x, y }, { inline: false });
186191
// [["x", "y"], "$0+$1", "$0*$1", "$2+$3"]
187192

188-
// 使用优化选项
189-
const optimized = compile(result, { x, y }, { optimize: true });
190-
// [["x", "y"], "($0+$1)+($0*$1)"]
193+
// 禁用短路求值
194+
const noShortCircuit = compile(result, { x, y }, { shortCircuit: false });
195+
// 生成的表达式将使用直接的运算符而非控制流节点
191196
```
192197

193198
### `evaluate<TResult>(data: CompiledData, values: Record<string, unknown>): TResult`

src/compile.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export interface CompileOptions {
2626
/**
2727
* 是否启用短路求值
2828
* 为 &&, ||, ??, 和三元表达式生成控制流节点
29-
* @default false
29+
* @default true
3030
*/
3131
shortCircuit?: boolean;
3232
}
@@ -62,7 +62,7 @@ export function compile<TResult>(
6262
variables: Record<string, Variable<z.ZodType>>,
6363
options: CompileOptions = {}
6464
): CompiledData {
65-
const { inline = true, shortCircuit = false } = options;
65+
const { inline = true, shortCircuit = true } = options;
6666
// 创建编译上下文
6767
const context: CompileContext = {
6868
variableOrder: [],

0 commit comments

Comments
 (0)