DEV Community

loading...

Discussion on: Daily Challenge #61 - Evolution Rate

Collapse
dak425 profile image
Donald Feury

All this talk of evolution makes me want to Go play Pokemon again. Holy crap I haven't played that in a long time!

rate.go

package evolution

import "fmt"

const (
    negative string = "A negative evolution of %.f%%."
    positive string = "A positive evolution of %.f%%."
    neutral  string = "No evolution."
)

// Rate indicates the evolution percentage based on the before and after values
func Rate(before float64, after float64) string {
    if before == 0 {
        return fmt.Sprintf(positive, after*100)
    }

    if after == 0 {
        return fmt.Sprintf(negative, before*100)
    }

    rate := (after - before) / before * 100

    if rate > 0 {
        return fmt.Sprintf(positive, rate)
    }

    if rate < 0 {
        return fmt.Sprintf(negative, rate*-1)
    }

    return neutral
}

rate_test.go

package evolution

import "testing"

type testCase struct {
    description string
    input       []float64
    expected    string
}

func TestRate(t *testing.T) {
    testCases := []testCase{
        {
            "a positive evolution rate",
            []float64{11.29, 45.79},
            "A positive evolution of 306%.",
        },
        {
            "a negative evolution rate",
            []float64{95.12, 66.84},
            "A negative evolution of 30%.",
        },
        {
            "zero before value",
            []float64{0, 27.35},
            "A positive evolution of 2735%.",
        },
        {
            "zero after value",
            []float64{41.26, 0},
            "A negative evolution of 4126%.",
        },
        {
            "same before and after values",
            []float64{1.26, 1.26},
            "No evolution.",
        },
    }

    for _, test := range testCases {
        if result := Rate(test.input[0], test.input[1]); result != test.expected {
            t.Fatalf("FAIL: %s - Rate(%+v): %s - expected: %s", test.description, test.input, result, test.expected)
        }
        t.Logf("PASS: %s", test.description)
    }
}

Collapse
aminnairi profile image
Amin

I always love your take at these challenges in Go. I should get started soon. Looking sharp as always!

And yes, Pokemon is just timelessly good. I could play it all my life haha!

Collapse
dak425 profile image
Donald Feury

Ah shucks, I am humbled by the praise.

You should, Go is a very easy language to pick up and use.

Only part that may require a little more effort to understand is the concurrency related features of it but just pick those up as you need them.