package utils

type BasicType interface {
	int | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | string
}

func InArray[T BasicType](needle T, hystack []T) bool {
	for _, item := range hystack {
		if needle == item {
			return true
		}
	}

	return false
}

func SliceArray[T any](arr []T, offset int, limit int) []T {
	size := len(arr)
	if size <= offset {
		return []T{}
	} else if size > offset && size < offset+limit {
		return arr[offset:size]
	} else {
		return arr[offset : offset+limit]
	}
}

func ToMap[K comparable, T any](arr []T, getKey func(*T) K) map[K]T {
	r := make(map[K]T)
	for _, v := range arr {
		k := getKey(&v)
		r[k] = v
	}
	return r
}

func IntersectionRate(a, b []int) float64 {
	setA := make(map[int]bool)
	setB := make(map[int]bool)
	intersection := make(map[int]bool)

	// 将 a 切片中的元素添加到 setA
	for _, value := range a {
		setA[value] = true
	}

	// 将 b 切片中的元素添加到 setB，并检查是否也在 setA 中
	for _, value := range b {
		setB[value] = true
		if setA[value] {
			intersection[value] = true
		}
	}

	// 计算交集大小
	intersectionSize := len(intersection)

	maxSize := len(a)
	if maxSize == 0 {
		return 0.0 // 避免除以零的情况
	}
	rate := float64(intersectionSize) / float64(maxSize)

	return rate
}
