Skip to content

Commit

Permalink
Update slice.DeepEqual and its unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
arybolovlev committed Jan 4, 2024
1 parent e3f6a0b commit b1b7eca
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 36 deletions.
27 changes: 16 additions & 11 deletions internal/slice/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,25 +26,30 @@ func DeepEqual[A any](a, b []A) bool {
}

if a == nil || b == nil {
return true
return cmp.Equal(a, b)
}

if reflect.TypeOf(a) != reflect.TypeOf(b) {
return false
}

for _, va := range a {
found := false
for _, vb := range b {
if cmp.Equal(va, vb) {
found = true
break
}
}
if !found {
ma := make(map[any]int)
mb := make(map[any]int)

for i := 0; i < len(a); i++ {
ma[a[i]]++
mb[b[i]]++
}

for va := range ma {
if _, ok := mb[va]; !ok {
return false
}
mb[va]--
if mb[va] == 0 {
delete(mb, va)
}
}

return true
return len(mb) == 0
}
77 changes: 52 additions & 25 deletions internal/slice/slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,44 +26,71 @@ func TestRemoveFromSlice(t *testing.T) {
}

func TestDeepEqual(t *testing.T) {
input := []map[string][]any{
cases := []struct {
A []any
B []any
Expected bool
}{
{
"A": {},
"B": {},
A: []any{},
B: []any{},
Expected: true,
},
{
"A": nil,
"B": nil,
A: nil,
B: nil,
Expected: true,
},
{
"A": {},
"B": nil,
A: []any{1, 2, 3},
B: []any{1, 2, 3},
Expected: true,
},
{
"A": {1, 2, 3},
"B": {1, 2, 3},
A: []any{1, 2, 3},
B: []any{3, 1, 2},
Expected: true,
},
{
"A": {"a", "b", "c"},
"B": {"b", "c"},
A: []any{},
B: nil,
Expected: false,
},
{
"A": {1, 2},
"B": {"b", "c"},
A: nil,
B: []any{1, 2, 3},
Expected: false,
},
{
A: []any{1, 1, 1, 2, 3},
B: []any{1, 1, 2, 2, 3},
Expected: false,
},
{
A: []any{"a", "b", "c"},
B: []any{"b", "c"},
Expected: false,
},
{
A: []any{1, 2},
B: []any{"b", "c"},
Expected: false,
},
{
A: []any{1, 1},
B: []any{1, 5},
Expected: false,
},
{
A: []any{1, 5},
B: []any{1, 1},
Expected: false,
},
}
want := []bool{
true,
true,
true,
true,
false,
false,
}
for i, s := range input {
r := DeepEqual(s["A"], s["B"])
if r != want[i] {
t.Errorf("The wanted result [%t] does not match with the produced [%v] at [%d]", want[i], r, i)
for i, s := range cases {
r := DeepEqual(s.A, s.B)
if r != s.Expected {
t.Errorf("The wanted result [%t] does not match with the produced [%v] at [%d]", s.Expected, r, i)
}
}
}

0 comments on commit b1b7eca

Please sign in to comment.