From 70e213b3f75127568c790e5310849960975923e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=83=91=E4=B8=80=E8=AF=BA=E5=A5=B9=E7=88=B8?= <649654639@qq.com> Date: Mon, 25 Jul 2022 20:52:33 +0800 Subject: [PATCH] feat:(slice add AppendIfAbsent function) (#52) Co-authored-by: george.zheng --- slice/slice.go | 8 ++++++++ slice/slice_test.go | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/slice/slice.go b/slice/slice.go index f140e99..eafb17b 100644 --- a/slice/slice.go +++ b/slice/slice.go @@ -851,3 +851,11 @@ func ToSlice[T any](value ...T) []T { } return out } + +// AppendIfAbsent only absent append the value +func AppendIfAbsent[T comparable](slices []T, value T) []T { + if !Contain(slices, value) { + slices = append(slices, value) + } + return slices +} diff --git a/slice/slice_test.go b/slice/slice_test.go index 543c60f..e2510ee 100644 --- a/slice/slice_test.go +++ b/slice/slice_test.go @@ -609,3 +609,11 @@ func TestToSlicePointer(t *testing.T) { assert.Equal([]*string{&str1}, ToSlicePointer(str1)) assert.Equal([]*string{&str1, &str2}, ToSlicePointer(str1, str2)) } + +func TestToAppendIfAbsent(t *testing.T) { + assert := internal.NewAssert(t, "TestToAppendIfAbsent") + + str1 := []string{"a", "b"} + assert.Equal([]string{"a", "b"}, AppendIfAbsent(str1, "a")) + assert.Equal([]string{"a", "b", "c"}, AppendIfAbsent(str1, "c")) +}