Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(set): pop method randomly removes an element and return #202

Merged
merged 1 commit into from
Mar 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions datastructure/set/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,11 @@ func (s Set[T]) EachWithBreak(iteratee func(item T) bool) {
// Pop delete the top element of set then return it, if set is empty, return nil-value of T and false.
func (s Set[T]) Pop() (v T, ok bool) {
if len(s) > 0 {
items := s.Values()
item := items[len(s)-1]
delete(s, item)
return item, true
for item := range s {
v = item
delete(s, item)
return v, true
}
}

return v, false
Expand Down
37 changes: 23 additions & 14 deletions datastructure/set/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,25 +243,34 @@ func TestEachWithBreak(t *testing.T) {
// assert.Equal(6, sum)
}

// func TestPop(t *testing.T) {
// assert := internal.NewAssert(t, "TestPop")
func TestPop(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestSet_Pop")

s := New[int]()

val, ok := s.Pop()
assert.Equal(0, val)
assert.Equal(false, ok)

// s := New[int]()
s = New(1, 2, 3, 4, 5)
sl := s.ToSlice()

// val, ok := s.Pop()
// assert.Equal(0, val)
// assert.Equal(false, ok)
val, ok = s.Pop()
assert.Equal(false, s.Contain(val))
assert.Equal(true, ok)
assert.Equal(len(sl)-1, s.Size())

// s.Add(1)
// s.Add(2)
// s.Add(3)
var found bool

// // s = New(1, 2, 3, 4, 5)
for _, v := range sl {
if v == val {
found = true
}
}

// val, ok = s.Pop()
// assert.Equal(3, val)
// assert.Equal(true, ok)
// }
assert.Equal(true, found)
}

func TestSet_ToSlice(t *testing.T) {
t.Parallel()
Expand Down
Loading