Debian Codegraph @

exslices/deduplicate.go

raw
1 // Copyright (c) 2024 Tulir Asokan
2 //
3 // This Source Code Form is subject to the terms of the Mozilla Public
4 // License, v. 2.0. If a copy of the MPL was not distributed with this
5 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7 package exslices
8
9 // DeduplicateUnsorted removes duplicates from the given slice without requiring that the input slice is sorted.
10 // The order of the output will be the same as the input. The input slice will not be modified.
11 //
12 // If you don't care about the order of the output, it's recommended to sort the list and then use [slices.Compact].
13 func DeduplicateUnsorted[T comparable](s []T) []T {
14 return deduplicateUnsortedInto(s, make([]T, 0, len(s)))
15 }
16
17 // DeduplicateUnsortedOverwrite removes duplicates from the given slice without requiring that the input slice is sorted.
18 // The input slice will be modified and used as the output slice to avoid extra allocations.
19 //
20 // If you don't care about the order of the output, it's recommended to sort the list and then use [slices.Compact].
21 func DeduplicateUnsortedOverwrite[T comparable](s []T) []T {
22 out := deduplicateUnsortedInto(s, s[:0])
23 clear(s[len(out):])
24 return out
25 }
26
27 func deduplicateUnsortedInto[T comparable](s, result []T) []T {
28 seen := make(map[T]struct{}, len(s))
29 for _, item := range s {
30 if _, ok := seen[item]; !ok {
31 seen[item] = struct{}{}
32 result = append(result, item)
33 }
34 }
35 return result
36 }
37
38 // DeduplicateUnsortedFunc removes duplicates from the given slice using the given key function without requiring
39 // that the input slice is sorted. The order of the output will be the same as the input.
40 //
41 // If you don't care about the order of the output, it's recommended to sort the list and then use [slices.CompactFunc].
42 func DeduplicateUnsortedFunc[T any, K comparable](s []T, getKey func(T) K) []T {
43 return deduplicateUnsortedFuncInto(s, make([]T, 0, len(s)), getKey)
44 }
45
46 // DeduplicateUnsortedOverwriteFunc removes duplicates from the given slice using the given key function
47 // without requiring that the input slice is sorted. The order of the output will be the same as the input.
48 // The input slice will be modified and used as the output slice to avoid extra allocations.
49 //
50 // If you don't care about the order of the output, it's recommended to sort the list and then use [slices.CompactFunc].
51 func DeduplicateUnsortedOverwriteFunc[T any, K comparable](s []T, getKey func(T) K) []T {
52 out := deduplicateUnsortedFuncInto(s, s[:0], getKey)
53 clear(s[len(out):])
54 return out
55 }
56
57 func deduplicateUnsortedFuncInto[T any, K comparable](s, result []T, getKey func(T) K) []T {
58 seen := make(map[K]struct{}, len(s))
59 for _, item := range s {
60 key := getKey(item)
61 if _, ok := seen[key]; !ok {
62 seen[key] = struct{}{}
63 result = append(result, item)
64 }
65 }
66 return result
67 }