增加in array能力

This commit is contained in:
白茶清欢 2023-03-30 14:49:38 +08:00
parent c886ff6b20
commit 6cee12a850
3 changed files with 75 additions and 1 deletions

50
array.go Normal file
View File

@ -0,0 +1,50 @@
// Package util ...
//
// Description : util ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-03-30 14:35
package util
import (
"fmt"
"reflect"
)
type array struct {
}
// In 判断指定数据是否在目标数据集中, 不存在返回 -1 , 存在时返回数据对应的索引
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:38 2023/3/30
func (a *array) In(search interface{}, source interface{}) int {
if nil == source {
return -1
}
list, ok := source.([]interface{})
if !ok {
return -1
}
if nil == search {
for idx, item := range list {
if item == nil {
return idx
}
}
return -1
}
searchType := reflect.TypeOf(search).Kind()
for idx, item := range list {
if searchType != reflect.TypeOf(item).Kind() {
// 类型不同
continue
}
if fmt.Sprintf("%v", search) == fmt.Sprintf("%v", item) {
return idx
}
}
return -1
}

20
array_test.go Normal file
View File

@ -0,0 +1,20 @@
// Package util ...
//
// Description : util ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-03-30 14:43
package util
import (
"fmt"
"testing"
)
func Test_array_In(t *testing.T) {
fmt.Println(Array.In(1234, []string{"1234", "123", "1"}))
fmt.Println(Array.In(1234, []interface{}{1234, "123", "1"}))
fmt.Println(Array.In(nil, []interface{}{1234, "123", "1"}))
fmt.Println(Array.In(nil, []interface{}{1234, "123", "1", nil}))
}

View File

@ -31,7 +31,9 @@ var (
// Calculate ...
Calculate *calculate
// Project ...
Project = &project{}
Project *project
// 数组操作
Array *array
)
func init() {
@ -46,4 +48,6 @@ func init() {
URL = &ownURL{}
Map = &ownMap{}
Calculate = &calculate{}
Project = &project{}
Array = &array{}
}