Evaluate ternary operator (tested)

This commit is contained in:
Umur Ozkul 2022-04-25 16:01:02 +02:00
parent c810c4576d
commit cbc2b73b20
2 changed files with 18 additions and 1 deletions

View File

@ -6,7 +6,7 @@ describe("Parse ternary operator", () => {
testParseToBe("2>1 ? 'YES' : 'NO'", "Ok((:$$ternary (:larger 2 1) 'YES' 'NO'))") testParseToBe("2>1 ? 'YES' : 'NO'", "Ok((:$$ternary (:larger 2 1) 'YES' 'NO'))")
}) })
Skip.describe("Evaluate ternary operator", () => { describe("Evaluate ternary operator", () => {
testEvalToBe("true ? 'YES' : 'NO'", "Ok('YES')") testEvalToBe("true ? 'YES' : 'NO'", "Ok('YES')")
testEvalToBe("false ? 'YES' : 'NO'", "Ok('NO')") testEvalToBe("false ? 'YES' : 'NO'", "Ok('NO')")
}) })

View File

@ -158,6 +158,21 @@ let dispatchMacroCall = (
| _ => replaceSymbols(expression, bindings) | _ => replaceSymbols(expression, bindings)
} }
let doTernary = (
conditionExpr: expression,
trueExpression: expression,
falseExpression: expression,
bindings: ExpressionT.bindings,
) => {
let rCondition = conditionExpr->reduceExpression(bindings)
rCondition->Result.flatMap(condition =>
switch condition {
| EvBool(true) => trueExpression->Ok
| EvBool(false) => falseExpression->Ok
| _ => RESyntaxError("Boolean value expected for conditional")->Error
}
)
}
switch list { switch list {
| list{ExpressionT.EValue(EvCall("$$bindings"))} => bindings->ExpressionT.EBindings->Ok | list{ExpressionT.EValue(EvCall("$$bindings"))} => bindings->ExpressionT.EBindings->Ok
@ -173,6 +188,8 @@ let dispatchMacroCall = (
expression, expression,
} => } =>
doBindExpression(expression, bindings) doBindExpression(expression, bindings)
| list{ExpressionT.EValue(EvCall("$$ternary")), conditionExpr, trueExpr, falseExpr} =>
doTernary(conditionExpr, trueExpr, falseExpr, bindings)
| _ => list->ExpressionT.EList->Ok | _ => list->ExpressionT.EList->Ok
} }
} }