Skip to content

Commit e8fe4b7

Browse files
committed
listequal
1 parent a8cd4de commit e8fe4b7

2 files changed

Lines changed: 68 additions & 2 deletions

File tree

utils.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ func ToMap[T any, K comparable](list []T, fn func(T) K) map[K][]T {
5050
return result
5151
}
5252

53-
func Distinct[T any](list []T) []T {
54-
seen := make(map[any]struct{})
53+
func Distinct[T comparable](list []T) []T {
54+
seen := make(map[T]struct{})
5555
result := make([]T, 0)
5656
for _, t := range list {
5757
if _, ok := seen[t]; !ok {
@@ -61,3 +61,15 @@ func Distinct[T any](list []T) []T {
6161
}
6262
return result
6363
}
64+
65+
func ListEqual[T comparable](a, b []T) bool {
66+
if len(a) != len(b) {
67+
return false
68+
}
69+
for i := range a {
70+
if a[i] != b[i] {
71+
return false
72+
}
73+
}
74+
return true
75+
}

utils_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,3 +261,57 @@ func TestDistinct(t *testing.T) {
261261
})
262262
}
263263
}
264+
265+
func TestListEqual(t *testing.T) {
266+
tests := []struct {
267+
name string
268+
a, b []int
269+
expected bool
270+
}{
271+
{
272+
name: "both empty",
273+
a: []int{},
274+
b: []int{},
275+
expected: true,
276+
},
277+
{
278+
name: "equal slices",
279+
a: []int{1, 2, 3},
280+
b: []int{1, 2, 3},
281+
expected: true,
282+
},
283+
{
284+
name: "different lengths",
285+
a: []int{1, 2},
286+
b: []int{1, 2, 3},
287+
expected: false,
288+
},
289+
{
290+
name: "same length, different elements",
291+
a: []int{1, 2, 3},
292+
b: []int{1, 2, 4},
293+
expected: false,
294+
},
295+
{
296+
name: "nil slices are equal",
297+
a: nil,
298+
b: nil,
299+
expected: true,
300+
},
301+
{
302+
name: "nil vs empty slice",
303+
a: nil,
304+
b: []int{},
305+
expected: true, // some people expect this to be true, some false — depends on your interpretation
306+
},
307+
}
308+
309+
for _, tt := range tests {
310+
t.Run(tt.name, func(t *testing.T) {
311+
result := ListEqual(tt.a, tt.b)
312+
if result != tt.expected {
313+
t.Errorf("ListEqual(%v, %v) = %v; want %v", tt.a, tt.b, result, tt.expected)
314+
}
315+
})
316+
}
317+
}

0 commit comments

Comments
 (0)