github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/isc/slice.go (about)

     1  package isc
     2  
     3  //SubList 分片截取
     4  func SubList[T any](list []T, fromIndex int, toIndex int) []T {
     5  	m := map[int]int{fromIndex: toIndex, toIndex: fromIndex}
     6  	start := fromIndex
     7  	if fromIndex < start {
     8  		start = toIndex
     9  	}
    10  	end := m[start]
    11  
    12  	if start < 0 {
    13  		start = 0
    14  	}
    15  	if start == end {
    16  		return []T{}
    17  	}
    18  	if end > len(list) {
    19  		return list[start:]
    20  	}
    21  	return list[start:end]
    22  }
    23  
    24  //Slice 分片截取,参数详情见 IntRange ,返回新分片
    25  func Slice[T any](list []T, r IntRange) []T {
    26  	return SubList(list, r.Start, r.End)
    27  }
    28  
    29  // SliceContains Returns true if element is found in the collection.
    30  //predicate keySelector
    31  //if you want to check item in list, please use ListContains
    32  func SliceContains[T any, K comparable](list []T, predicate func(T) K, key K) bool {
    33  	m := SliceTo(list, predicate)
    34  	_, ok := m[key]
    35  	return ok
    36  }
    37  
    38  func IsInSlice[T comparable](list []T, val T) bool {
    39  	return IndexOf(list, val) >= 0
    40  }
    41  
    42  func SliceToMap[T comparable](list []T) map[T]T {
    43  	m := make(map[T]T)
    44  	for _, e := range list {
    45  		m[e] = e
    46  	}
    47  	return m
    48  }
    49  
    50  func SliceTo[T any, K comparable](list []T, valueTransform func(T) K) map[K]T {
    51  	m := make(map[K]T)
    52  	for _, e := range list {
    53  		m[valueTransform(e)] = e
    54  	}
    55  	return m
    56  }
    57  
    58  func SliceDistinct[T any](list []T) []T {
    59  	result := NewList[T]()
    60  	for _, k := range list {
    61  		if !result.Contains(k) {
    62  			result.Add(k)
    63  		}
    64  	}
    65  	return result
    66  }
    67  
    68  //SliceDistinctTo Returns a list containing only distinct elements from the given collection.
    69  //Among equal elements of the given collection, only the last one will be present in the resulting list.
    70  //The elements in the resulting list are not in the same order as they were in the source collection.
    71  func SliceDistinctTo[T any, V comparable](list []T, valueTransform func(T) V) []T {
    72  	m := SliceTo(list, valueTransform)
    73  	var result []T
    74  	for _, v := range m {
    75  		result = append(result, v)
    76  	}
    77  	return result
    78  }