modelRT/util/string.go

58 lines
1.7 KiB
Go

// Package util provide some utility functions
package util
// RemoveTargetsFromSliceSimple define func to remove targets from a slice
func RemoveTargetsFromSliceSimple[T comparable](targetsSlice []T, targetsToRemove []T) []T {
targetsToRemoveSet := SliceToSet(targetsToRemove)
for i := len(targetsSlice) - 1; i >= 0; i-- {
if _, found := targetsToRemoveSet[targetsSlice[i]]; found {
targetsSlice[i] = targetsSlice[len(targetsSlice)-1]
targetsSlice = targetsSlice[:len(targetsSlice)-1]
}
}
return targetsSlice
}
// SliceToSet define func to convert a slice to a set
func SliceToSet[T comparable](targetsSlice []T) map[T]struct{} {
set := make(map[T]struct{}, len(targetsSlice))
for _, target := range targetsSlice {
set[target] = struct{}{}
}
return set
}
// DeduplicateAndReportDuplicates define func to deduplicate a slice and report duplicates
func DeduplicateAndReportDuplicates[T comparable](targetsSlice []T, sourceSlice []T) (deduplicated []T, duplicates []T) {
targetSet := SliceToSet(targetsSlice)
deduplicated = make([]T, 0, len(sourceSlice))
// duplicate items slice
duplicates = make([]T, 0, len(sourceSlice))
for _, source := range sourceSlice {
if _, found := targetSet[source]; found {
duplicates = append(duplicates, source)
continue
}
deduplicated = append(deduplicated, source)
}
return deduplicated, duplicates
}
// GetLongestCommonPrefixLength define func of get longest common prefix length between two strings
func GetLongestCommonPrefixLength(query string, result string) int {
if query == "" {
return 0
}
minLen := min(len(query), len(result))
for i := range minLen {
if query[i] != result[i] {
return i
}
}
return minLen
}