mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
- Add `Chunk` to split slices into groups of size n. - Add `ContainsBy` for predicate-based containment checks. - Add `UniqueBy` to deduplicate slices by key selector. - Add `ParallelMap` for concurrent mapping with context and error handling. - Add `maps.Keys` and `maps.Values` helpers for extracting map keys/values. - Update README and docs for new features. - Refactor `Contains` to use `slices.Contains`.
16 lines
445 B
Go
16 lines
445 B
Go
package underscore
|
|
|
|
// UniqueBy returns a slice of unique values from the given slice using a key selector.
|
|
// The first occurrence of each key is kept and order is preserved.
|
|
func UniqueBy[T any, K comparable](values []T, key func(T) K) (uniques []T) {
|
|
seen := make(map[K]struct{})
|
|
for _, v := range values {
|
|
k := key(v)
|
|
if _, ok := seen[k]; ok {
|
|
continue
|
|
}
|
|
seen[k] = struct{}{}
|
|
uniques = append(uniques, v)
|
|
}
|
|
return uniques
|
|
}
|