initial commit
This commit is contained in:
75
pkg/array/diff.go
Normal file
75
pkg/array/diff.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package array
|
||||
|
||||
func Diff[T comparable](slice1, slice2 []T) []T {
|
||||
var result []T
|
||||
|
||||
elementsMap := make(map[T]bool)
|
||||
for _, v := range slice2 {
|
||||
elementsMap[v] = true
|
||||
}
|
||||
|
||||
for _, v := range slice1 {
|
||||
if !elementsMap[v] {
|
||||
result = append(result, v)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func MapDiff[T comparable](slice1, slice2 []T) []T {
|
||||
var result []T
|
||||
|
||||
arr1elementsMap := make(map[T]int)
|
||||
for _, v := range slice1 {
|
||||
arr1elementsMap[v] += 1
|
||||
}
|
||||
|
||||
arr2elementsMap := make(map[T]int)
|
||||
for _, v := range slice2 {
|
||||
arr2elementsMap[v] += 1
|
||||
}
|
||||
|
||||
for key, count1 := range arr1elementsMap {
|
||||
if count2, ok := arr2elementsMap[key]; !ok || count2 != count1 {
|
||||
result = append(result, key)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// DiffByKeyAndValue returns the elements from slice1 that do not have
|
||||
// corresponding elements in slice2 based on a key and a comparison function.
|
||||
// T1 and T2 are the types of the elements in slice1 and slice2 respectively.
|
||||
// K is the type of the key used for comparison.
|
||||
func DiffByKeyAndValue[T1 any, T2 any, K comparable](
|
||||
slice1 []T1,
|
||||
slice2 []T2,
|
||||
getKeyFromSlice1 func(T1) K,
|
||||
getKeyFromSlice2 func(T2) K,
|
||||
compare func(T1, T2) bool,
|
||||
) []T1 {
|
||||
// Create a map to index elements of slice2 by their keys
|
||||
indexedSlice2 := make(map[K]T2)
|
||||
for _, elementFromSlice2 := range slice2 {
|
||||
key := getKeyFromSlice2(elementFromSlice2)
|
||||
indexedSlice2[key] = elementFromSlice2
|
||||
}
|
||||
|
||||
// Initialize a slice to hold the elements that are different
|
||||
var differingElements []T1
|
||||
|
||||
// Iterate over slice1 and find elements that are not in slice2
|
||||
for _, elementFromSlice1 := range slice1 {
|
||||
key := getKeyFromSlice1(elementFromSlice1)
|
||||
|
||||
// Check if the key exists in the indexed slice2
|
||||
if correspondingElementFromSlice2, exists := indexedSlice2[key]; !exists || !compare(elementFromSlice1, correspondingElementFromSlice2) {
|
||||
// If it doesn't exist or the comparison fails, add to the result
|
||||
differingElements = append(differingElements, elementFromSlice1)
|
||||
}
|
||||
}
|
||||
|
||||
return differingElements
|
||||
}
|
||||
Reference in New Issue
Block a user