All files / json-expression/src/operators branching.ts

100% Statements 11/11
100% Branches 5/5
100% Functions 4/4
100% Lines 10/10

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 333x     3x           23x     7x 7x 7x 7x 5x                 3x     1x        
import {Expression, type ExpressionResult, Literal} from '../codegen-steps';
import type * as types from '../types';
 
export const branchingOperators: types.OperatorDefinition<any>[] = [
  [
    '?',
    ['if'],
    3,
    (expr: types.ExprIf, ctx) => {
      return ctx.eval(expr[1], ctx) ? ctx.eval(expr[2], ctx) : ctx.eval(expr[3], ctx);
    },
    (ctx: types.OperatorCodegenCtx<types.ExprIf>): ExpressionResult => {
      const condition = ctx.operands[0];
      const then = ctx.operands[1];
      const otherwise = ctx.operands[2];
      if (condition instanceof Literal) return condition.val ? then : otherwise;
      return new Expression(`(${condition})?(${then}):(${otherwise})`);
    },
  ] as types.OperatorDefinition<types.ExprIf>,
 
  [
    'throw',
    [],
    1,
    (expr: types.ExprThrow, ctx) => {
      throw ctx.eval(expr[1], ctx);
    },
    (ctx: types.OperatorCodegenCtx<types.ExprThrow>): ExpressionResult => {
      return new Expression(`(function(){throw (${ctx.operands[0]})})()`);
    },
  ] as types.OperatorDefinition<types.ExprThrow>,
];