From dd03646f9ae5f60814ef32cee6a43020156fcd49 Mon Sep 17 00:00:00 2001 From: Max Kovalevskii Date: Thu, 21 Mar 2024 23:10:44 +0100 Subject: [PATCH] added opc example (package) --- README.md | 4 +++- opc/opc.go | 23 ++++++++++++++++++++ opc/opc_test.go | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 opc/opc.go create mode 100644 opc/opc_test.go diff --git a/README.md b/README.md index e1e1db6..68789aa 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,9 @@ Grokking Go Fundamentals with Tests Video Series / Course - [A new learning way on how to write "Hello, World!" program in Go](https://www.youtube.com/watch?v=EECXgocw4N0) - [Source Code (helloworld)](./helloworld/) - [Everything You Need to Know to Start Writing Tests In Go With TDD (For Go Beginners)](https://www.youtube.com/watch?v=Fr9xox_soKQ&t=794s) - - [Source Code](./calculator/) + - [Source Code (calculator)](./calculator/) +- [Let's learn variables and constants in Go with tests and TDD. Part 1](https://www.youtube.com/watch?v=9bny23btS2s&t=422s) + - [Source Code (opc)](./opc/) [Link on YouTube Playlist](https://www.youtube.com/playlist?list=PLCqcI2Ic-eM_4ma__dXm4xX3P9fgQ2V9C) diff --git a/opc/opc.go b/opc/opc.go new file mode 100644 index 0000000..581cc64 --- /dev/null +++ b/opc/opc.go @@ -0,0 +1,23 @@ +package opc + +import "fmt" + +const discountRate float64 = 0.9 + +func CalculateOrderPrice( + itemPrice float64, + quantity int, + taxRate float64, + discount bool, +) string { + totalPrice := itemPrice * float64(quantity) + + if discount { + totalPrice = totalPrice * discountRate + } + + taxAmount := totalPrice * taxRate + finalPrice := totalPrice + taxAmount + + return fmt.Sprintf("The final price is: €%.2f", finalPrice) +} diff --git a/opc/opc_test.go b/opc/opc_test.go new file mode 100644 index 0000000..397d26d --- /dev/null +++ b/opc/opc_test.go @@ -0,0 +1,56 @@ +package opc_test + +import ( + "go-sandbox/opc" + "testing" + "fmt" +) + +func TestCalculateOrderPrice(t *testing.T) { + type testCase struct { + itemPrice, taxRate float64 + quantity int + discount bool + want string + } + + testCases := []testCase{ + { + itemPrice: 2.99, + taxRate: 0.07, + quantity: 3, + discount: true, + want: "The final price is: €8.64", + }, + { + itemPrice: 2.99, + taxRate: 0.07, + quantity: 3, + discount: false, + want: "The final price is: €9.60", + }, + } + + for _, tc := range testCases { + tcName := fmt.Sprintf( + "itemPrice = %.2f, quantity = %d, taxRate = %.2f, discount = %t", + tc.itemPrice, + tc.quantity, + tc.taxRate, + tc.discount, + ) + + t.Run(tcName, func (t *testing.T) { + got := opc.CalculateOrderPrice( + tc.itemPrice, + tc.quantity, + tc.taxRate, + tc.discount, + ) + + if tc.want != got { + t.Errorf("Failed! Wanted %q, got %q", tc.want, got) + } + }) + } +}