diff options
| author | Sam Anthony <sam@samanthony.xyz> | 2023-07-29 10:37:40 -0230 |
|---|---|---|
| committer | Sam Anthony <sam@samanthony.xyz> | 2023-07-29 10:37:40 -0230 |
| commit | 0e1cd2b6a328887c1a630eae0b34366a607bb1b8 (patch) | |
| tree | 70825addc206c7b7e7fae33bbc0f86ab24534ee8 /op.go | |
| parent | 5b81647c27af77be3d35e10cb53cad1897a7f392 (diff) | |
| download | pfc-0e1cd2b6a328887c1a630eae0b34366a607bb1b8.zip | |
refactor
Diffstat (limited to 'op.go')
| -rw-r--r-- | op.go | 43 |
1 files changed, 43 insertions, 0 deletions
@@ -0,0 +1,43 @@ +package main + +import ( + "fmt" + "math" +) + +// parseOp returns a closure that performs the specified arithmetic operation, +// or OpError if op is not a valid operator. +func parseOp(op byte) (func(lhs *float64, rhs float64), error) { + switch op { + case '+': + return func(lhs *float64, rhs float64) { *lhs += rhs }, nil + case '-': + return func(lhs *float64, rhs float64) { *lhs -= rhs }, nil + case '*': + return func(lhs *float64, rhs float64) { *lhs *= rhs }, nil + case '/': + return func(lhs *float64, rhs float64) { + if rhs != 0 { + *lhs /= rhs + } + }, nil + case '%': + return func(lhs *float64, rhs float64) { + if rhs != 0 { + *lhs = float64(int64(*lhs) % int64(rhs)) + } + }, nil + case '^': + return func(lhs *float64, rhs float64) { *lhs = math.Pow(*lhs, rhs) }, nil + } + return nil, OpError{op} +} + +// OpError records an invalid arithmetic operator. +type OpError struct { + c byte +} + +func (e OpError) Error() string { + return fmt.Sprintf("invalid operator: %c", e.c) +} |