Skip to content

Commit

Permalink
Implemented short-circuit coalesce/ternary
Browse files Browse the repository at this point in the history
  • Loading branch information
Knetic committed May 1, 2017
1 parent 9f400ba commit d534c6b
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
26 changes: 18 additions & 8 deletions EvaluableExpression.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
)

const isoDateFormat string = "2006-01-02T15:04:05.999999999Z0700"
const shortCircuitHolder int = -1

var DUMMY_PARAMETERS = MapParameters(map[string]interface{}{})

Expand Down Expand Up @@ -162,7 +163,6 @@ func (this EvaluableExpression) evaluateStage(stage *evaluationStage, parameters

var left, right interface{}
var err error
var shortResult bool

if stage.leftStage != nil {
left, err = this.evaluateStage(stage.leftStage, parameters)
Expand All @@ -171,23 +171,33 @@ func (this EvaluableExpression) evaluateStage(stage *evaluationStage, parameters
}
}

if stage.isShortCircuitable() && isBool(left) {

shortResult = left.(bool)

if stage.isShortCircuitable() {
switch stage.symbol {
case AND:
if !shortResult {
if left == false {
return false, nil
}
case OR:
if shortResult {
if left == true {
return true, nil
}
case COALESCE:
if left != nil {
return left, nil
}

case TERNARY_TRUE:
if left == false {
right = shortCircuitHolder
}
case TERNARY_FALSE:
if left != nil {
right = shortCircuitHolder
}
}
}

if stage.rightStage != nil {
if right != shortCircuitHolder && stage.rightStage != nil {
right, err = this.evaluateStage(stage.rightStage, parameters)
if err != nil {
return nil, err
Expand Down
22 changes: 22 additions & 0 deletions evaluation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,28 @@ func TestParameterizedEvaluation(test *testing.T) {
},
Expected: false,
},
EvaluationTest{

Name: "Short-circuit ternary",
Input: "true ? 1 : fail()",
Functions: map[string]ExpressionFunction{
"fail": func(arguments ...interface{}) (interface{}, error) {
return nil, errors.New("Did not short-circuit")
},
},
Expected: 1.0,
},
EvaluationTest{

Name: "Short-circuit coalesce",
Input: "'foo' ?? fail()",
Functions: map[string]ExpressionFunction{
"fail": func(arguments ...interface{}) (interface{}, error) {
return nil, errors.New("Did not short-circuit")
},
},
Expected: "foo",
},
}

runEvaluationTests(evaluationTests, test)
Expand Down

0 comments on commit d534c6b

Please sign in to comment.