DEV Community

loading...

Discussion on: Daily Challenge #54 - What century is it?

Collapse
dak425 profile image
Donald Feury

Insert Go Pun Here

century.go

package century

import (
    "strconv"
)

// Century gives the text representation of what century the given date belongs to
func Century(date int) string {
    // if date is negative (BC), convert to positive
    if date < 0 {
        date *= -1
    }
    prefix := date/100 + 1

    var suffix string

    // if its one the weird teens centuries, suffix is "th"
    switch prefix % 100 {
    case 11, 12, 13:
        suffix = "th"
    default:
        switch prefix % 10 {
        case 1:
            suffix = "st"
        case 2:
            suffix = "nd"
        case 3:
            suffix = "rd"
        default:
            suffix = "th"
        }
    }

    return strconv.Itoa(prefix) + suffix
}

century_test.go

package century

import "testing"

func TestCentury(t *testing.T) {
    testCases := []struct {
        description string
        input       int
        expected    string
    }{
        {
            "twenty third centry",
            2259,
            "23rd",
        },
        {
            "twelfth century",
            1124,
            "12th",
        },
        {
            "twenty first century",
            2000,
            "21st",
        },
        {
            "small centry",
            24,
            "1st",
        },
        {
            "odd centry name",
            1013,
            "11th",
        },
        {
            "large odd century name",
            11013,
            "111th",
        },
        {
            "negative century",
            -2000,
            "21st",
        },
    }

    for _, test := range testCases {
        if result := Century(test.input); result != test.expected {
            t.Fatalf("FAIL: %s - Centry(%d): %s - expected '%s'", test.description, test.input, result, test.expected)
        }
        t.Logf("PASS: %s", test.description)
    }
}