Skip to content

Commit

Permalink
AddIfNotExists 如果元素不存在,则添加元素
Browse files Browse the repository at this point in the history
  • Loading branch information
steden committed Dec 14, 2024
1 parent a838fc4 commit c07f295
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 9 additions & 0 deletions test/collection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c07f295

Please sign in to comment.