github.com/searKing/golang/go@v1.2.117/exp/slices/uniq.go (about) 1 // Copyright 2022 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slices 6 7 // Uniq returns a slice satisfying c != zero within all c in the slice. 8 // Uniq modifies the contents of the slice s; it does not create a new slice. 9 func Uniq[S ~[]E, E comparable](s S) S { 10 if len(s) == 0 { 11 return s 12 } 13 m := make(map[E]bool) 14 for _, v := range s { 15 m[v] = true 16 } 17 18 i := 1 19 m[s[0]] = false 20 for _, v := range s[1:] { 21 save, has := m[v] 22 if has && save { 23 s[i] = v 24 m[v] = false 25 i++ 26 } 27 } 28 return s[:i] 29 } 30 31 // UniqFunc returns a slice satisfying f(c) within all c in the slice. 32 func UniqFunc[S ~[]E, E any](s S, f func(v1, v2 E) bool) S { 33 if len(s) == 0 { 34 return s 35 } 36 37 i := 1 38 for _, v := range s[1:] { 39 if ContainsFunc(s[:i], func(e E) bool { return f(v, e) }) { 40 continue 41 } 42 s[i] = v 43 i++ 44 } 45 return s[:i] 46 }