Last active
September 24, 2025 19:30
-
-
Save duboisf/24d96f2a5f0cad0934bb0eea41982de1 to your computer and use it in GitHub Desktop.
Generic golang functions to do a unique sort of elements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package sort | |
| // SortedUniqueFunc returns a sorted list of unique elements extracted from the input slice using the provided getter function. | |
| func SortedUniqueFunc[T any, E cmp.Ordered](ts []T, get func(T) E) []E { | |
| elems := make(map[E]struct{}) | |
| for _, t := range ts { | |
| elem := get(t) | |
| elems[elem] = struct{}{} | |
| } | |
| return slices.Sorted(maps.Keys(elems)) | |
| } | |
| // SortedUnique returns a sorted list of unique elements from the input slice. | |
| func SortedUnique[T cmp.Ordered](ts []T) []T { | |
| return SortedUniqueFunc(ts, Identity) | |
| } | |
| // Identity is the identity function that returns the input as is. | |
| // Can be used for the [SortedUniqueFunc] function when the input slice is of a comparable type. | |
| // Inspired by haskell's id function. | |
| func Identity[E any](e E) E { | |
| return e | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment