Skip to content

Commit

Permalink
Add simple Key function for slice functions
Browse files Browse the repository at this point in the history
...where the key and element types are the same, eg string, int etc.
This saves the caller having to do:

  func(e string) string {
      return e
  }

Signed-off-by: Tom Pantelis <[email protected]>
  • Loading branch information
tpantelis authored and sridhargaddam committed Oct 25, 2023
1 parent 44c404b commit 47ffc6b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 10 deletions.
4 changes: 4 additions & 0 deletions pkg/slices/slices.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,7 @@ func mapFrom[E any, K comparable](s []E, key func(E) K) map[K]bool {

return m
}

func Key[K comparable](k K) K {
return k
}
16 changes: 6 additions & 10 deletions pkg/slices/slices_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type Status struct {
var _ = Describe("Intersect", func() {
Specify("with non-empty slices", func() {
testIntersect := func(s1, s2 []string, exp ...string) {
actual := slices.Intersect(s1, s2, key)
actual := slices.Intersect(s1, s2, slices.Key[string])
Expect(set.New(actual...).Equal(set.New(exp...))).To(BeTrue(), "Expected: %s. Actual: %s", exp, actual)
}

Expand All @@ -45,16 +45,16 @@ var _ = Describe("Intersect", func() {
})

Specify("with empty an slice", func() {
Expect(slices.Intersect([]string{"1"}, []string{}, key)).To(BeEmpty())
Expect(slices.Intersect([]string{"1"}, nil, key)).To(BeEmpty())
Expect(slices.Intersect([]string{}, []string{"1"}, key)).To(BeEmpty())
Expect(slices.Intersect(nil, []string{"1"}, key)).To(BeEmpty())
Expect(slices.Intersect([]string{"1"}, []string{}, slices.Key[string])).To(BeEmpty())
Expect(slices.Intersect([]string{"1"}, nil, slices.Key[string])).To(BeEmpty())
Expect(slices.Intersect([]string{}, []string{"1"}, slices.Key[string])).To(BeEmpty())
Expect(slices.Intersect(nil, []string{"1"}, slices.Key[string])).To(BeEmpty())
})
})

var _ = Specify("Union", func() {
testUnion := func(s1, s2 []string, exp ...string) {
actual := slices.Union(s1, s2, key)
actual := slices.Union(s1, s2, slices.Key[string])
Expect(actual).To(Equal(exp))
}

Expand Down Expand Up @@ -173,10 +173,6 @@ var _ = Describe("Equivalent", func() {
})
})

func key(e string) string {
return e
}

func statusKey(s Status) string {
return s.Name
}

0 comments on commit 47ffc6b

Please sign in to comment.