Skip to content

Commit

Permalink
sets: add Add() method
Browse files Browse the repository at this point in the history
Part of PCI-3790
  • Loading branch information
marco-m-pix4d committed May 15, 2024
1 parent d64c735 commit 78d52de
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [v0.12.2] - UNRELEASED

### Added

- pkg/sets: add Intersect() and Add() methods.

## [v0.12.1] - 2024-04-03

### Minor breaking change
Expand Down
9 changes: 9 additions & 0 deletions sets/sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ func (s *Set[T]) Contains(item T) bool {
return found
}

// Add inserts item into s. Returns true if the item was present.
func (s *Set[T]) Add(item T) bool {
if s.Contains(item) {
return true
}
s.items[item] = struct{}{}
return false
}

// Remove deletes item from s. Returns true if the item was present.
func (s *Set[T]) Remove(item T) bool {
if !s.Contains(item) {
Expand Down
38 changes: 38 additions & 0 deletions sets/sets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,3 +271,41 @@ func TestRemoveNotFound(t *testing.T) {
t.Run(tc.name, func(t *testing.T) { test(t, tc) })
}
}

func TestAdd(t *testing.T) {
type testCase struct {
name string
items []int
wantList []int
}

test := func(t *testing.T, tc testCase) {
s := sets.New[int](5)
for _, item := range tc.items {
s.Add(item)
}
qt.Assert(t, qt.DeepEquals(s.OrderedList(), tc.wantList))
}

testCases := []testCase{
{
name: "one item",
items: []int{3},
wantList: []int{3},
},
{
name: "multiple items",
items: []int{3, 0, 42},
wantList: []int{0, 3, 42},
},
{
name: "duplicates",
items: []int{10, 5, 5, 10, 1},
wantList: []int{1, 5, 10},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { test(t, tc) })
}
}

0 comments on commit 78d52de

Please sign in to comment.