Skip to content

Instantly share code, notes, and snippets.

@docwhat
Last active July 20, 2022 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save docwhat/e3b13265d24471651e02f7d7a42e7d2c to your computer and use it in GitHub Desktop.
Save docwhat/e3b13265d24471651e02f7d7a42e7d2c to your computer and use it in GitHub Desktop.
module gist.github.com/e3b13265d24471651e02f7d7a42e7d2c
go 1.18
// main.go
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func comparePeopleByName(people []Person) func(int, int) bool {
return func(i, j int) bool {
return people[i].Name < people[j].Name
}
}
func comparePeopleByAge(people []Person) func(int, int) bool {
return func(i, j int) bool {
return people[i].Age < people[j].Age
}
}
func main() {
people := []Person{
{"Gopher", 7},
{"Alice", 55},
{"Vera", 24},
{"Bob", 75},
}
sort.Slice(people, comparePeopleByName(people))
fmt.Println("By name:", people)
sort.Slice(people, comparePeopleByAge(people))
fmt.Println("By age:", people)
}
// main_test.go
package main
import "testing"
func TestComparePeopleByName(t *testing.T) {
testCases := []struct {
desc string
a, b Person
expected bool
}{
{"a < b", Person{"bob", 1}, Person{"krabs", 2}, true},
{"a > b", Person{"krabs", 1}, Person{"bob", 2}, false},
{"a = a", Person{"plankton", 1}, Person{"plankton", 2}, false},
}
for _, testCase := range testCases {
t.Run(testCase.desc, func(t *testing.T) {
people := []Person{testCase.a, testCase.b}
got := comparePeopleByName(people)(0, 1)
if testCase.expected != got {
t.Errorf("expected %v, got %v", testCase.expected, got)
}
})
}
}
func TestComparePeopleByAge(t *testing.T) {
testCases := []struct {
desc string
a, b Person
expected bool
}{
{"a < b", Person{"sandy", 10}, Person{"patrick", 20}, true},
{"a > b", Person{"sandy", 30}, Person{"patrick", 20}, false},
{"a = b", Person{"sandy", 90}, Person{"patrick", 90}, false},
}
for _, testCase := range testCases {
t.Run(testCase.desc, func(t *testing.T) {
people := []Person{testCase.a, testCase.b}
got := comparePeopleByAge(people)(0, 1)
if testCase.expected != got {
t.Errorf("expected %v, got %v", testCase.expected, got)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment