Files
latosa-escrima/backend/utils/get_diff.go

43 lines
994 B
Go

package utils
import (
"log"
)
// GetDiff returns two slices: elements to add and elements to remove
func GetDiff[T comparable](current, newm []T) ([]T, []T) {
log.Println(current, newm)
// Use a single map with an int to track state:
// 1: only in current, 2: only in new, 3: in both
presence := make(map[T]int)
// Mark all items in current as 1
for _, item := range current {
presence[item] = 1
}
// Update map based on newm: add 2 if not present, set to 3 if present
for _, item := range newm {
if val, exists := presence[item]; exists {
presence[item] = val + 2 // 1 -> 3 (both)
} else {
presence[item] = 2 // only in new
}
}
var toAdd, toRemove []T
// Iterate once over the map to build results
for item, state := range presence {
switch state {
case 1: // Only in current -> remove
toRemove = append(toRemove, item)
case 2: // Only in new -> add
toAdd = append(toAdd, item)
// case 3: in both, do nothing
}
}
return toAdd, toRemove
}