Skip to content

Commit

Permalink
增加 noerr 函数
Browse files Browse the repository at this point in the history
  • Loading branch information
dengsgo committed Oct 22, 2019
1 parent 9171875 commit 345d594
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
15 changes: 15 additions & 0 deletions engine/def.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ var defFunC = map[string]int{
"sqrt": 1,
"cbrt": 1,

"noerr": 1,

"max": 2,
"min": 2,
}
Expand All @@ -51,6 +53,8 @@ func init() {
"sqrt": defSqrt,
"cbrt": defCbrt,

"noerr": defNoerr,

"max": defMax,
"min": defMin,
}
Expand Down Expand Up @@ -130,3 +134,14 @@ func defMin(expr []ExprAST) float64 {
func p2(expr []ExprAST) (float64, float64) {
return ExprASTResult(expr[0]), ExprASTResult(expr[1])
}

// noerr(1/0) = 0
// noerr(2.5/(1-1)) = 0
func defNoerr(expr []ExprAST) (r float64) {
defer func() {
if e := recover(); e != nil {
r = 0
}
}()
return ExprASTResult(expr[0])
}
4 changes: 4 additions & 0 deletions engine/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ func TestParseAndExecSimple(t *testing.T) {
{"min(2^3,3+abs(-1)*6)", 8},
{"max(2^3,3^2)", 9},
{"min(2^3,3^2)", 8},
{"noerr(1/0)", 0},
{"noerr(1/(1-1))", 0},
}
for _, e := range exprs {
r, _ := ParseAndExec(e.Expr)
Expand Down Expand Up @@ -118,6 +120,8 @@ func TestParseAndExecError(t *testing.T) {
"max(1,)",
"min(1,)",
"min(1,3, 099)",
"1/0",
"99.9 / (2-1-1)",
}
for _, e := range exprs {
_, err := ParseAndExec(e)
Expand Down
10 changes: 10 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,13 @@ func TestExecQ(t *testing.T) {
exp := "2e-3*2+2e2+1"
exec(exp)
}

func TestExecR(t *testing.T) {
exp := "3.8 - 56 / (1-1) - 4"
exec(exp)
}

func TestExecS(t *testing.T) {
exp := "noerr(3.8 - 56 / (1-1) - 4)"
exec(exp)
}

0 comments on commit 345d594

Please sign in to comment.