DEV Community

Discussion on: Daily Challenge #48 - Facebook Likes

Collapse
 
dak425 profile image
Donald Feury • Edited

More Go with tests:

likes.go

package likes

import "fmt"

// Likes takes a slice of people who like a post and returns a string indicating who likes it
func Likes(list []string) string {
    likeLen := len(list)

    switch likeLen {
    case 0:
        return "no one likes this"
    case 1:
        return fmt.Sprintf("%s likes this", list[0])
    case 2:
        return fmt.Sprintf("%s and %s like this", list[0], list[1])
    case 3:
        return fmt.Sprintf("%s, %s, and %s like this", list[0], list[1], list[2])
    default:
        return fmt.Sprintf("%s, %s, and %d others like this", list[0], list[1], likeLen-2)
    }
}

likes_test.go

package likes

import (
    "testing"
)

var testCases = []struct {
    description string
    input       []string
    expected    string
}{
    {
        "no likes",
        []string{},
        "no one likes this",
    },
    {
        "one like",
        []string{"Mark"},
        "Mark likes this",
    },
    {
        "two likes",
        []string{"Mark", "Jeff"},
        "Mark and Jeff like this",
    },
    {
        "three likes",
        []string{"Mark", "Jeff", "Bob"},
        "Mark, Jeff, and Bob like this",
    },
    {
        "many likes",
        []string{"Mark", "Jeff", "Bob", "Alice", "Susan"},
        "Mark, Jeff, and 3 others like this",
    },
}

func TestLikes(t *testing.T) {
    for _, test := range testCases {
        if result := Likes(test.input); result != test.expected {
            t.Fatalf("FAIL: %s - Likes(%v): %s, expected: %s \n", test.description, test.input, result, test.expected)
        }
        t.Logf("PASS: %s \n", test.description)
    }
}