@@ -9,34 +9,25 @@ package pie
99// The added and removed returned may be blank respectively, or contain upto as
1010// many elements that exists in the largest slice.
1111func Diff [T comparable ](ss []T , against []T ) (added , removed []T ) {
12- // This is probably not the best way to do it. We do an O(n^2) between the
13- // slices to see which items are missing in each direction.
14-
1512 diffOneWay := func (ss1 , ss2raw []T ) (result []T ) {
16- ss2 := make ([]T , len (ss2raw ))
17- copy (ss2 , ss2raw )
13+ set := make (map [T ]struct {}, len (ss1 ))
1814
1915 for _ , s := range ss1 {
20- found := false
21-
22- for i , element := range ss2 {
23- if s == element {
24- ss2 = append (ss2 [:i ], ss2 [i + 1 :]... )
25- found = true
26- break
27- }
28- }
16+ set [s ] = struct {}{}
17+ }
2918
30- if ! found {
19+ for _ , s := range ss2raw {
20+ if _ , ok := set [s ]; ok {
21+ delete (set , s ) // remove duplicates
22+ } else {
3123 result = append (result , s )
3224 }
3325 }
34-
3526 return
3627 }
3728
38- removed = diffOneWay (ss , against )
39- added = diffOneWay (against , ss )
29+ added = diffOneWay (ss , against )
30+ removed = diffOneWay (against , ss )
4031
4132 return
4233}
0 commit comments