1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

feat: add EqualUnordered

This commit is contained in:
dudaodong
2024-12-19 19:36:17 +08:00
parent 1f64e02df4
commit ab89f0aee1
5 changed files with 120 additions and 0 deletions

View File

@@ -220,6 +220,28 @@ func EqualWith[T, U any](slice1 []T, slice2 []U, comparator func(T, U) bool) boo
return true
}
// EqualUnordered checks if two slices are equal: the same length and all elements' value are equal (unordered).
// Play: todo
func EqualUnordered[T comparable](slice1, slice2 []T) bool {
if len(slice1) != len(slice2) {
return false
}
seen := make(map[T]int)
for _, v := range slice1 {
seen[v]++
}
for _, v := range slice2 {
if seen[v] == 0 {
return false
}
seen[v]--
}
return true
}
// Every return true if all of the values in the slice pass the predicate function.
// Play: https://go.dev/play/p/R8U6Sl-j8cD
func Every[T any](slice []T, predicate func(index int, item T) bool) bool {

View File

@@ -1300,3 +1300,15 @@ func ExampleConcatBy() {
// Alice | Bob | Charlie
// 90
}
func ExampleEqualUnordered() {
result1 := EqualUnordered([]int{1, 2, 3}, []int{3, 2, 1})
result2 := EqualUnordered([]int{1, 2, 3}, []int{4, 5, 6})
fmt.Println(result1)
fmt.Println(result2)
// Output:
// true
// false
}

View File

@@ -1926,3 +1926,25 @@ func TestConcatBy(t *testing.T) {
assert.Equal(90, result.Age)
})
}
func TestEqualUnordered(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestEqualUnordered")
tests := []struct {
slice1, slice2 []int
expected bool
}{
{[]int{}, []int{}, true},
{[]int{1, 2, 3}, []int{1, 2, 3}, true},
{[]int{1, 2, 3}, []int{3, 2, 1}, true},
{[]int{1, 2, 3}, []int{1, 2, 3, 4}, false},
{[]int{1, 2, 3}, []int{1, 2}, false},
{[]int{1, 2, 3}, []int{1, 2, 4}, false},
}
for _, test := range tests {
assert.Equal(test.expected, EqualUnordered(test.slice1, test.slice2))
}
}