Example Diff slices generic with removed or added result
#useful_code
test
➖➖➖➖➖➖➖➖
🕊 @gopher_academy | @GolangEngineers
#useful_code
func Diff[T comparable](listA, listB []T) (removed, added []T) {
mapA := make(map[T]bool)
mapB := make(map[T]bool)
for _, item := range listA {
mapA[item] = true
}
for _, item := range listB {
mapB[item] = true
}
for item := range mapA {
if !mapB[item] {
removed = append(removed, item)
}
}
for item := range mapB {
if !mapA[item] {
added = append(added, item)
}
}
return removed, added
}
test
func TestDiff(t *testing.T) {
tests := []struct {
name string
listA []string
listB []string
result struct {
removed []string
added []string
}
}{
{
name: "b removed and e added",
listA: []string{"a", "b", "c", "d"},
listB: []string{"a", "c", "d", "e"},
result: struct{ removed, added []string }{removed: []string{"b"}, added: []string{"e"}},
},
{
name: "No Differences",
listA: []string{"a", "b", "c"},
listB: []string{"a", "b", "c"},
result: struct{ removed, added []string }{removed: nil, added: nil},
},
{
name: "Items Only in List B",
listA: []string{"a"},
listB: []string{"a", "b", "c"},
result: struct{ removed, added []string }{removed: nil, added: []string{"b", "c"}},
},
{
name: "Empty Lists",
listA: []string{},
listB: []string{},
result: struct{ removed, added []string }{removed: nil, added: nil},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
removed, added := Diff(tt.listA, tt.listB)
if !reflect.DeepEqual(removed, tt.result.removed) {
t.Errorf("Removed items mismatch. Expected %v, got %v", tt.result.removed, removed)
}
if !reflect.DeepEqual(added, tt.result.added) {
t.Errorf("Added items mismatch. Expected %v, got %v", tt.result.added, added)
}
})
}
}
➖➖➖➖➖➖➖➖
🕊 @gopher_academy | @GolangEngineers
👍6