From 0cbb3dd97e62f1a0873aa4deec40a5c41c3a9df1 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Mon, 13 Jun 2022 14:06:20 +0800 Subject: [PATCH] feat: add Equal function for slice --- slice/slice.go | 15 +++++++++++++++ slice/slice_test.go | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index fcad15d..df06646 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -147,6 +147,21 @@ func DifferenceWith[T any](slice []T, comparedSlice []T, comparator func(value, return res } +// Equal checks if two slices are equal: the same length and all elements' order and value are equal +func Equal[T comparable](slice1, slice2 []T) bool { + if len(slice1) != len(slice2) { + return false + } + + for i := range slice1 { + if slice1[i] != slice2[i] { + return false + } + } + + return true +} + // Every return true if all of the values in the slice pass the predicate function. func Every[T any](slice []T, predicate func(index int, item T) bool) bool { if predicate == nil { diff --git a/slice/slice_test.go b/slice/slice_test.go index 8980374..e75283a 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -68,6 +68,17 @@ func TestConcat(t *testing.T) { // assert.Equal([]int{1, 2, 3, 4, 5}, Concat([]int{1, 2, 3}, []int{4}, 5)) } +func TestEqual(t *testing.T) { + assert := internal.NewAssert(t, "TestEqual") + + slice1 := []int{1, 2, 3} + slice2 := []int{1, 2, 3} + slice3 := []int{3, 2, 1} + + assert.Equal(true, Equal(slice1, slice2)) + assert.Equal(false, Equal(slice1, slice3)) +} + func TestEvery(t *testing.T) { nums := []int{1, 2, 3, 5} isEven := func(i, num int) bool {