Skip to content

Commit

Permalink
Add calculator challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
plutov committed Aug 30, 2024
1 parent aef0a7e commit 12d6c22
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ Follow me on [https://packagemain.tech](packagemain.tech) to read other stuff I
- [x] ([@shogg](https://github.com/shogg)) [nasacollage](https://github.com/plutov/practice-go/tree/master/nasacollage)
- [x] ([@shogg](https://github.com/shogg)) [node_degree](https://github.com/plutov/practice-go/tree/master/node_degree)
- [ ] [compression](https://github.com/plutov/practice-go/tree/master/compression)
- [ ] [calculator](https://github.com/plutov/practice-go/tree/master/calculator)

### Run tests with benchmarks

Expand Down
31 changes: 31 additions & 0 deletions calculator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
### Calculator

Create a calculator that can evaluate simple mathematical expressions. The calculator should be able to handle the basic arithmetic operations: addition, subtraction, multiplication, and division.

### Function

```go
Eval(expr string) (float64, error)
```

### Examples

```go
result, err := Eval("1 + 2")
fmt.Println(result) // 3

result, err := Eval("2 * 3")
fmt.Println(result) // 6

result, err := Eval("10 / 2 + 6")
fmt.Println(result) // 11

result, err := Eval("( 2 + 3 ) * 4")
fmt.Println(result) // 20
```

### Run tests with benchmarks

```
go test -bench .
```
5 changes: 5 additions & 0 deletions calculator/calculator.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package calculator

func Eval(expr string) (float64, error) {
return 3.0, nil
}
38 changes: 38 additions & 0 deletions calculator/calculator_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package calculator

import "testing"

var tests = []struct {
expr string
result float64
isErrNil bool
}{
{"1 + 2", 3.0, true},
{"(2 + 1) - (-3) * 4", 15.0, true},
{"(2 + 1) - (-3) * 4 +", 0.0, false},
{"", 0.0, false},
{"1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10", 55.0, true},
{"() + ()", 0.0, false},
{"(1 + 2) + (3 + 4)", 10.0, true},
{"((5 - 2) * 3 + 1) / ((3 + 1) - 2)", 5.0, true},
}

func TestEval(t *testing.T) {
for _, tt := range tests {
t.Run(tt.expr, func(t *testing.T) {
result, err := Eval(tt.expr)
if result != tt.result {
t.Errorf("Eval(%s) got %f, want %f", tt.expr, result, tt.result)
}
if (err == nil) != tt.isErrNil {
t.Errorf("Eval(%s) got error %v, want error %v", tt.expr, err, tt.isErrNil)
}
})
}
}

func BenchmarkEval(b *testing.B) {
for i := 0; i < b.N; i++ {
Eval("(2 + (1)) - (-3) * 4")
}
}

0 comments on commit 12d6c22

Please sign in to comment.