DEV Community

Discussion on: Daily Challenge #260 - Subtract the Sum

Collapse
 
aminnairi profile image
Amin • Edited

Go

EDIT: just realized this challenge was a trap, but leaving the (wrong) solution here for people wanting to try out Go (it's awesome, try it).

Commands for initializing the project.

$ mkdir $GOPATH/src/fruits
$ cd $GOPATH/src/fruits
$ touch fruits.go

The source-code.

// Set of utilities for manipulating fruits.
package fruits

// Find a fruit based on its index.
func FindFromInteger(integer uint16) string {
    if integer < 9 {
        switch (integer) {
        case 1:
            return "kiwi"

        case 2:
            return "pear"

        case 3:
            return "kiwi"

        case 4:
            return "banana"

        case 5:
            return "melon"

        case 6:
            return "banana"

        case 7:
            return "melon"

        case 8:
            return "pineapple"
        }
    }

    return "apple"
}

Commands for the unit tests.

$ touch fruits_test.go

The source-code for unit tests.

package fruits_test

import "testing"
import "fruits"
import "fmt"

func TestFindFromInteger(t *testing.T) {
    var valuesExpectations map[uint16]string = map[uint16]string{
        0: "apple",
        1: "kiwi",
        2: "pear",
        3: "kiwi",
        4: "banana",
        5: "melon",
        6: "banana",
        7: "melon",
        8: "pineapple",
        9: "apple",
        10: "apple",
        100: "apple",
        1_000: "apple",
        325: "apple",
        10_000: "apple",
    }

    for value, expectation := range valuesExpectations {
        var result string = fruits.FindFromInteger(value)

        if result != expectation {
            t.Errorf("Expected fruits.FindFromInteger(%d) to equal %s but got %s.", value, expectation, result)
        }
    }
}

func BenchmarkFindFromInteger(b *testing.B) {
    for index := 0; index < b.N; index++ {
        fruits.FindFromInteger(10_000)
    }
}

func ExampleFindFromInteger() {
    fmt.Printf("Fruit for index %d is %q.\n", 15, "apple")
    // Output: Fruit for index 15 is "apple".
}

Commands for the tests, benchmark and coverage.

$ go test -cover -bench .
goos: linux
goarch: amd64
pkg: fruits
BenchmarkFindFromInteger-4      482598516                2.58 ns/op
PASS
coverage: 100.0% of statements
ok      fruits  1.500s