From c07f29593d864a59e45b5cd43ded3e97598ca79f Mon Sep 17 00:00:00 2001 From: steden <1470804@qq.com> Date: Sat, 14 Dec 2024 15:58:58 +0800 Subject: [PATCH] =?UTF-8?q?AddIfNotExists=20=E5=A6=82=E6=9E=9C=E5=85=83?= =?UTF-8?q?=E7=B4=A0=E4=B8=8D=E5=AD=98=E5=9C=A8=EF=BC=8C=E5=88=99=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E5=85=83=E7=B4=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- collection.go | 13 +++++++++++++ test/collection_test.go | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/collection.go b/collection.go index 6975e92..ab6e9df 100644 --- a/collection.go +++ b/collection.go @@ -21,6 +21,19 @@ func (receiver *Collection[T]) Add(item ...T) { } } +// AddIfNotExists 如果元素不存在,则添加元素 +func (receiver *Collection[T]) AddIfNotExists(item T) { + receiver.lock.Lock() + defer receiver.lock.Unlock() + + for _, t := range *receiver.source { + if parse.IsEqual(t, item) { + return + } + } + *receiver.source = append(*receiver.source, item) +} + // AddRange 添加元素 func (receiver *Collection[T]) AddRange(lst Enumerable[T]) { if lst.Count() > 0 { diff --git a/test/collection_test.go b/test/collection_test.go index 28802d5..32aedcd 100644 --- a/test/collection_test.go +++ b/test/collection_test.go @@ -23,6 +23,15 @@ func Test_collection_Add(t *testing.T) { assert.Equal(t, 3, lst.Index(2)) } +func Test_collection_AddIfNotExists(t *testing.T) { + lst := collections.NewList[int](1, 2) + lst.AddIfNotExists(1) + lst.AddIfNotExists(2) + lst.AddIfNotExists(3) + assert.Equal(t, 3, lst.Count()) + assert.Equal(t, 3, lst.Index(2)) +} + func Test_collection_AddRange(t *testing.T) { lst := collections.NewList[int]() lst2 := collections.NewList[int](1, 2, 3)