From 0e1cd2b6a328887c1a630eae0b34366a607bb1b8 Mon Sep 17 00:00:00 2001 From: Sam Anthony Date: Sat, 29 Jul 2023 10:37:40 -0230 Subject: refactor --- op.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 op.go (limited to 'op.go') diff --git a/op.go b/op.go new file mode 100644 index 0000000..ab57a84 --- /dev/null +++ b/op.go @@ -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) +} -- cgit v1.2.3