Browse Source

【杨】增加切片去重

master v0.2.7
yangzm 2 years ago
parent
commit
4f8a7b43df
2 changed files with 38 additions and 0 deletions
  1. +32
    -0
      slice.go
  2. +6
    -0
      slice_test.go

+ 32
- 0
slice.go View File

@ -3,6 +3,11 @@
*/
package helper
import (
"errors"
"fmt"
)
// 求差集
func Diff(slice1, slice2 []string) []string {
m := make(map[string]int)
@ -52,5 +57,32 @@ func Union(slice1, slice2 []string) []string {
}
}
return slice1
}
func Unique(originals interface{}) (interface{}, error) {
temp := map[string]struct{}{}
switch slice := originals.(type) {
case []string:
result := make([]string, 0, len(originals.([]string)))
for _, item := range slice {
key := fmt.Sprint(item)
if _, ok := temp[key]; !ok {
temp[key] = struct{}{}
result = append(result, item)
}
}
return result, nil
case []int64:
result := make([]int64, 0, len(originals.([]int64)))
for _, item := range slice {
key := fmt.Sprint(item)
if _, ok := temp[key]; !ok {
temp[key] = struct{}{}
result = append(result, item)
}
}
return result, nil
default:
return nil, errors.New(fmt.Sprintf("Unknown type: %T", slice))
}
}

+ 6
- 0
slice_test.go View File

@ -25,3 +25,9 @@ func Test_Union(t *testing.T) {
cc := Union(aa, bb)
fmt.Println(cc)
}
func Test_Unique(t *testing.T) {
var str = []string{"1", "2", "2"}
ret, err := Unique(str)
fmt.Println(ret, err)
}

Loading…
Cancel
Save