diff --git a/handler/handler.go b/handler/handler.go index cb14e31..456ca82 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -15,6 +15,9 @@ type Handler struct { } func (this *Handler) Handle(args []string) error { + if this.calculator == nil { + return fmt.Errorf("%w: calculator is required", ErrNilCalculator) + } if len(args) != 2 { return fmt.Errorf("%w: two args req (you provided %d", ErrTooFewArgs, len(args)) } @@ -23,6 +26,7 @@ func (this *Handler) Handle(args []string) error { if err != nil { return fmt.Errorf("%w: first arg (%s) %w", ErrMalformedArgs, a, err) } + b, err := strconv.Atoi(args[1]) if err != nil { return fmt.Errorf("%w: first arg (%s) %w", ErrMalformedArgs, b, err) @@ -37,7 +41,7 @@ func (this *Handler) Handle(args []string) error { return nil } -func NewHandler(output io.Writer, calculator calc.Addition) *Handler { +func NewHandler(output io.Writer, calculator calc.Calculator) *Handler { return &Handler{ calculator: calculator, output: output, @@ -48,4 +52,5 @@ var ( ErrTooFewArgs = errors.New("\"Usage: \"") ErrMalformedArgs = errors.New("invalid argument") ErrOutputWriter = errors.New("output write failed") + ErrNilCalculator = errors.New("nil calculator") ) diff --git a/main.go b/main.go index c7fc903..0e0455f 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + "flag" "log" "os" @@ -9,8 +10,18 @@ import ( ) func main() { - err := handler.NewHandler(os.Stdout, calc.Addition{}).Handle(os.Args[1:]) + var op string + flag.StringVar(&op, "op", "+", "One of + - * /") + flag.Parse() + err := handler.NewHandler(os.Stdout, calculators[op]).Handle(flag.Args()) if err != nil { log.Fatal(err) } } + +var calculators = map[string]calc.Calculator{ + "+": calc.Addition{}, + "-": calc.Subtraction{}, + "*": calc.Multiplication{}, + "/": calc.Division{}, +} diff --git a/main_test.go b/main_test.go index 95c03a0..b6fbde2 100644 --- a/main_test.go +++ b/main_test.go @@ -6,8 +6,8 @@ import ( "reflect" "testing" - calc "calc-lib/calc" - handler "calc-lib/handler" + "github.com/JacobMcKenzieSmarty/calc-lib/calc" + "github.com/JacobMcKenzieSmarty/calc-lib/handler" ) func assertEqual(t *testing.T, expected, actual any) { @@ -51,6 +51,12 @@ func TestOutputWriterError(t *testing.T) { assertError(t, taco, err) } +func TestNilCalculator(t *testing.T) { + myHandler := handler.NewHandler(&bytes.Buffer{}, nil) + err := myHandler.Handle([]string{"1", "2"}) + assertError(t, handler.ErrNilCalculator, err) +} + func TestHappyPath(t *testing.T) { myBuffer := new(bytes.Buffer) myHandler := handler.NewHandler(myBuffer, calc.Addition{})