You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In daily development, the Map, Filter, and Reduce functions provided by FP are indeed very useful, but there may be identical elements in the arrays or slices used in business, so I have to deduplicate the arrays. Because FP does not provide deduplication functionality, I can only use the closure function to deduplicate when writing the Map myself, which is not very convenient. So I wrote functions for array and slice deduplication.
The text was updated successfully, but these errors were encountered:
// Calls a defined by function on each element of an array, and returns an array with all element distinct.
func Unique[T any, K comparable](by func(T) K) func([]T) []T {
return func(xs []T) []T {
result := make([]T, 0, len(xs))
// unique map
m := make(map[K]struct{}, len(xs))
for _, item := range xs {
key := by(item)
if _, ok := m[key]; ok {
continue
}
m[key] = struct{}{}
result = append(result, item)
}
return result
}
In daily development, the Map, Filter, and Reduce functions provided by FP are indeed very useful, but there may be identical elements in the arrays or slices used in business, so I have to deduplicate the arrays. Because FP does not provide deduplication functionality, I can only use the closure function to deduplicate when writing the Map myself, which is not very convenient. So I wrote functions for array and slice deduplication.
The text was updated successfully, but these errors were encountered: