diff --git a/CHANGELOG.md b/CHANGELOG.md index fe2554d4..4b928b9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,9 @@ ### 12.120.0 -- `[knf]` Added `Alias` method +- `[knf]` Added methods `Alias` and `Config.Alias` - `[knf]` Added property name validation for all getters +- `[sliceutil]` Added method `IsEqual` - `[knf]` Code refactoring - `[knf]` Added more tests diff --git a/sliceutil/example_test.go b/sliceutil/example_test.go index 41d1cb22..864f392a 100644 --- a/sliceutil/example_test.go +++ b/sliceutil/example_test.go @@ -17,28 +17,40 @@ func ExampleCopy() { s1 := []string{"A", "B", "C"} s2 := Copy(s1) - fmt.Printf("%v", s2) + fmt.Printf("%v\n", s2) // Output: [A B C] } +func ExampleIsEqual() { + s1 := []int{1, 2, 3, 4} + s2 := []int{1, 2, 3, 4} + s3 := []int{1, 3, 2, 4} + + fmt.Printf("%v == %v → %t\n", s1, s2, IsEqual(s1, s2)) + fmt.Printf("%v == %v → %t\n", s2, s3, IsEqual(s2, s3)) + // Output: + // [1 2 3 4] == [1 2 3 4] → true + // [1 2 3 4] == [1 3 2 4] → false +} + func ExampleStringToInterface() { s := []string{"A", "B"} - fmt.Printf("%v", StringToInterface(s)) + fmt.Printf("%v\n", StringToInterface(s)) // Output: [A B] } func ExampleIntToInterface() { s := []int{1, 2} - fmt.Printf("%v", IntToInterface(s)) + fmt.Printf("%v\n", IntToInterface(s)) // Output: [1 2] } func ExampleErrorToString() { s := []error{fmt.Errorf("error1")} - fmt.Printf("%v", ErrorToString(s)) + fmt.Printf("%v\n", ErrorToString(s)) // Output: [error1] } diff --git a/sliceutil/sliceutil.go b/sliceutil/sliceutil.go index 9ed47ff0..0bdc468d 100644 --- a/sliceutil/sliceutil.go +++ b/sliceutil/sliceutil.go @@ -26,6 +26,24 @@ func Copy[K comparable](slice []K) []K { return s } +// IsEqual compares two slices and returns true if the slices are equal +func IsEqual[K comparable](s1, s2 []K) bool { + switch { + case s1 == nil && s2 == nil: + return true + case len(s1) != len(s2): + return false + } + + for i := range s1 { + if s1[i] != s2[i] { + return false + } + } + + return true +} + // StringToInterface converts slice with strings to slice with any func StringToInterface(data []string) []any { if len(data) == 0 { diff --git a/sliceutil/sliceutil_test.go b/sliceutil/sliceutil_test.go index 28ad796d..0dbf8a37 100644 --- a/sliceutil/sliceutil_test.go +++ b/sliceutil/sliceutil_test.go @@ -35,6 +35,22 @@ func (s *SliceSuite) TestCopy(c *C) { c.Assert(Copy([]string{"A"}), DeepEquals, []string{"A"}) } +func (s *SliceSuite) TestIsEqual(c *C) { + s1 := []int{1, 2, 3, 4} + s2 := []int{1, 2, 3, 4} + s3 := []int{1, 3, 2, 4} + s4 := []int{1, 2, 3} + + var s5, s6 []int + + c.Assert(IsEqual(s1, nil), Equals, false) + c.Assert(IsEqual(nil, s2), Equals, false) + c.Assert(IsEqual(s1, s2), Equals, true) + c.Assert(IsEqual(s1, s3), Equals, false) + c.Assert(IsEqual(s1, s4), Equals, false) + c.Assert(IsEqual(s5, s6), Equals, true) +} + func (s *SliceSuite) TestStringToInterface(c *C) { source := []string{"1", "2", "3"}