Add fundamentals

This commit is contained in:
Kasper Juul Hermansen 2022-02-23 00:07:11 +01:00
commit 64f5d8346d
Signed by: kjuulh
GPG Key ID: 0F95C140730F2F23
3 changed files with 159 additions and 0 deletions

View File

@ -0,0 +1,16 @@
package calculator
// Add takes two numbers and returns the result of adding them together.
func Add(a, b float64) float64 {
return a + b
}
// Subtract takes two numbers and returns the result of subtracting the second
// from the first.
func Subtract(a, b float64) float64 {
return b - a
}
func Multiply(a, b float64) float64 {
return a * b
}

View File

@ -0,0 +1,140 @@
package calculator
import (
"fmt"
"testing"
)
type testData struct {
want float64
a float64
b float64
}
func TestAdd(t *testing.T) {
t.Parallel()
td := []testData{
testData{
want: 4,
a: 2,
b: 2,
},
testData{
want: 2,
a: 1,
b: 1,
},
testData{
want: 3,
a: 1,
b: 2,
},
testData{
want: 0,
a: -1,
b: 1,
},
testData{
want: -1.5,
a: -1,
b: -.5,
},
}
for _, data := range td {
t.Run(fmt.Sprintf("(a:%f,b:%f)->want:%f", data.a, data.b, data.want), func(t *testing.T) {
got := Add(data.a, data.b)
if data.want != got {
t.Errorf("want %f, got %f", data.want, got)
}
})
}
}
func TestSubtract(t *testing.T) {
t.Parallel()
td := []testData{
{
want: -2,
a: 4,
b: 2,
},
{
want: 2,
a: 2,
b: 4,
},
{
want: 0,
a: 4,
b: 4,
},
{
want: 1.5,
a: 1,
b: 2.5,
},
{
want: -1.5,
a: -1,
b: -2.5,
},
}
for _, data := range td {
t.Run(fmt.Sprintf("(a:%f,b:%f)->want:%f", data.a, data.b, data.want), func(t *testing.T) {
got := Subtract(data.a, data.b)
if data.want != got {
t.Errorf("want %f, got %f", data.want, got)
}
})
}
}
func TestMultiply(t *testing.T) {
t.Parallel()
want := 8.
got := Multiply(2, 4)
if want != got {
t.Errorf("want %f, got %f", want, got)
}
}
func TestMultiplyOverflows(t *testing.T) {
t.Parallel()
td := []testData{
{
want: 2,
a: 1,
b: 2,
},
{
want: 8,
a: 2,
b: 4,
},
{
want: -8,
a: -2,
b: 4,
},
{
want: 1.5,
a: 0.5,
b: 3,
},
{
want: 0,
a: 8,
b: 0,
},
}
for _, data := range td {
t.Run(fmt.Sprintf("(a:%f,b:%f)->want:%f", data.a, data.b, data.want), func(t *testing.T) {
got := Multiply(data.a, data.b)
if data.want != got {
t.Errorf("want %f, got %f", data.want, got)
}
})
}
}

3
ftl-fundamentals/go.mod Normal file
View File

@ -0,0 +1,3 @@
module ftl-fundamentals
go 1.17