JInt (Javascript interpreter for .NET) with multistatement in Formula

540 Views Asked by At

I try to use JInt (Javascript Interpreter for .NET) with simple expression:

var engineTest = new Engine ()
    .SetValue ("X", 10.1)
    .SetValue ("Y", 20.5)
    .SetValue ("Code", "A");
    var dFormula = @"if (Code === 'A'){X+Y;} if (Code === 'B'){Y-X;}";
var result = engineTest.Execute(dFormula).GetCompletionValue();

for this Formula result will be 'undefined'. If I change dFormula to

var dFormula = @"if (Code === 'A'){X+Y;}";

or

var dFormula = @"if (Code === 'A'){X+Y;} else if (Code === 'B'){Y-X;}";

result will be correct. What's wrong with JInt (2.5.0). Or may be it doesn't support multiple statement in Formula? I tried to wrap Formula with "{}" bracket with no result.

2

There are 2 best solutions below

0
On BEST ANSWER

The reason is: Before executing each statement JInt resets Complition value. So, this formula will work only if Code === "B", otherwise result will be overwritten with 'undefined' value.

There are 2 ways to fix it:

  1. Combine into single statement (use else).
  2. Add to formula output variable, like

    var dFormula = @"if (Code === 'A'){RESULT = X+Y;} if (Code === 'B'){RESULT = Y-X;}";

0
On

Why not use return:

if (Code === 'A') return X+Y;
if (Code === 'B') return Y-X;

or

return Code === 'A' ? X+Y : (Code === 'B' ? Y-X : undefined);

or using a switch

switch (Code) {
    case a:
...