-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionRuntime.ts
More file actions
51 lines (45 loc) · 1.4 KB
/
ExpressionRuntime.ts
File metadata and controls
51 lines (45 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import type {Expr, Literal, JsonExpressionCodegenContext, JsonExpressionExecutionContext} from './types';
import type {OperatorRegistry} from './OperatorRegistry';
import {createEvaluate} from './createEvaluate';
/**
* Runtime for evaluating JSON expressions using a specified operator registry.
*/
export class ExpressionRuntime {
private evaluateFn: ReturnType<typeof createEvaluate>;
constructor(
private registry: OperatorRegistry,
private options: JsonExpressionCodegenContext = {}
) {
this.evaluateFn = createEvaluate({
operators: registry.asMap(),
...options
});
}
/**
* Evaluate a JSON expression.
*/
evaluate(
expr: Expr | Literal<unknown>,
ctx: JsonExpressionExecutionContext & JsonExpressionCodegenContext = {vars: undefined as any}
): unknown {
return this.evaluateFn(expr, {...this.options, ...ctx});
}
/**
* Get the operator registry used by this runtime.
*/
getRegistry(): OperatorRegistry {
return this.registry;
}
/**
* Create a new runtime with a different registry.
*/
withRegistry(registry: OperatorRegistry): ExpressionRuntime {
return new ExpressionRuntime(registry, this.options);
}
/**
* Create a new runtime with different options.
*/
withOptions(options: JsonExpressionCodegenContext): ExpressionRuntime {
return new ExpressionRuntime(this.registry, {...this.options, ...options});
}
}