os-autoinst / openqa-mon

Collection of terminal monitoring utilities for openQA
12 stars 13 forks source link

Consider a generic implementation of Unique() func #175

Open ilmanzo opened 1 month ago

ilmanzo commented 1 month ago

with reference to:

https://github.com/os-autoinst/openqa-mon/blob/900c7149e563b8ea972d59f22e520ea0d513a46e/cmd/openqa-mon/util.go#L44

and https://github.com/os-autoinst/openqa-mon/blob/900c7149e563b8ea972d59f22e520ea0d513a46e/cmd/openqa-mon/util.go#L56

a sample implementation with generics types (introduced in Go 1.18) that also avoids allocating a map of bools:

func unique[T comparable](slice []T) []T {
    seen := make(map[T]struct{})
    unique := []T{}

    for _, item := range slice {
        if _, exists := seen[item]; !exists {
            seen[item] = struct{}{}
            unique = append(unique, item)
        }
    }

    return unique
}

to call it:

uniqueInts := unique([]int{1, 2, 2, 3, 4, 4, 5})
uniqueStrings := unique([]string{"apple", "banana", "apple", "cherry"})
uniqueFloat64s := unique([]float64{1.1, 2.2, 2.2, 3.3, 4.4})
ilmanzo commented 1 month ago

Opening this issue only to have your opinion, if you like the idea I will follow up with a Pull Request :)

grisu48 commented 1 month ago

This would be a great refactoring idea. I think the code still originates from the pre-generics time, or at least when we used a go version that didn't had generics.

Feel free to open a PR :slightly_smiling_face: