github.com/searKing/golang/go@v1.2.74/container/slice/distinct.go (about) 1 // Copyright 2020 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 slice 6 7 import ( 8 "github.com/searKing/golang/go/util/object" 9 ) 10 11 // DistinctFunc returns a slice consisting of the distinct elements (according to 12 // {@link Object#equals(Object)}) of this slice. 13 func DistinctFunc(s interface{}, f func(interface{}, interface{}) int) interface{} { 14 return normalizeSlice(distinctFunc(Of(s), f), s) 15 } 16 17 // distinctFunc is the same as DistinctFunc except that if 18 //// truth==false, the sense of the predicate function is 19 //// inverted. 20 func distinctFunc(s []interface{}, f func(interface{}, interface{}) int) []interface{} { 21 object.RequireNonNil(s, "distinctFunc called on nil slice") 22 object.RequireNonNil(f, "distinctFunc called on nil callfn") 23 24 sDistinctMap := map[interface{}]struct{}{} 25 var sDistincted = []interface{}{} 26 for _, r := range s { 27 if _, ok := sDistinctMap[r]; ok { 28 continue 29 } 30 sDistinctMap[r] = struct{}{} 31 sDistincted = append(sDistincted, r) 32 } 33 return sDistincted 34 }