function calculate()

in packages/sqrl/src/ast/astIntersects.ts [16:56]


function calculate(ast: Ast, values) {
  if (ast.type === "feature") {
    invariant(
      typeof values[ast.value] === "boolean",
      "Expected feature to be set"
    );
    return values[ast.value];
  } else if (ast.type === "not") {
    return !calculate(ast.expr, values);
  } else if (ast.type === "boolean_expr") {
    if (ast.operator === "and") {
      return calculate(ast.left, values) && calculate(ast.right, values);
    } else if (ast.operator === "or") {
      return calculate(ast.left, values) || calculate(ast.right, values);
    } else {
      throw new Error("Unknown ast operator during calculate step");
    }
  } else if (ast.type === "binary_expr") {
    if (ast.left.type !== "feature") {
      throw new Error("Expected feature on left hand side");
    }
    if (ast.right.type !== "constant") {
      throw new Error("Expected constant on right hand side");
    }

    invariant(
      typeof values[ast.left.value] === "string",
      "Expected non-boolean value"
    );
    const value = values[ast.left.value] === ast.right.value;
    if (ast.operator === "=") {
      return value;
    } else if (ast.operator === "!=") {
      return !value;
    } else {
      throw new Error("Unknown binary_expr operator");
    }
  } else {
    throw new Error("Unexpected ast type during truth table calculate step");
  }
}