All files / json-expression/src createEvaluate.ts

95.45% Statements 21/22
100% Branches 4/4
100% Functions 2/2
94.44% Lines 17/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  3x   3x 1223x       6634x 2849x   2675x 2675x   2675x 2675x 2675x 2675x 2535x       162x 3x 3x 3x       1223x    
import type {Expr, JsonExpressionCodegenContext, JsonExpressionExecutionContext, Literal, OperatorMap} from './types';
import * as util from './util';
 
export const createEvaluate = ({operators, createPattern}: {operators: OperatorMap} & JsonExpressionCodegenContext) => {
  const evaluate = (
    expr: Expr | Literal<unknown>,
    ctx: JsonExpressionExecutionContext & JsonExpressionCodegenContext,
  ): unknown => {
    if (!(expr instanceof Array)) return expr;
    if (expr.length === 1) return expr[0];
 
    const fn = expr[0];
    const def = operators.get(fn);
 
    try {
      if (def) {
        const [name, , arity, fn] = def;
        util.assertArity(name, arity, expr);
        return fn(expr, {createPattern, ...ctx, eval: evaluate});
      }
      throw new Error('Unknown expression:' + JSON.stringify(expr));
    } catch (err) {
      if (err instanceof Error) throw err;
      const error = new Error('Expression evaluation error.');
      (<any>error).value = err;
      throw error;
    }
  };
 
  return evaluate;
};