1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-04 12:52:28 +08:00

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

This commit is contained in:
Cannian
2024-03-17 10:28:25 +08:00
committed by GitHub
parent 004dbdc32e
commit 2b765b49e0
2 changed files with 28 additions and 18 deletions

View File

@@ -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. // 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) { func (s Set[T]) Pop() (v T, ok bool) {
if len(s) > 0 { if len(s) > 0 {
items := s.Values() for item := range s {
item := items[len(s)-1] v = item
delete(s, item) delete(s, item)
return item, true return v, true
}
} }
return v, false return v, false

View File

@@ -243,25 +243,34 @@ func TestEachWithBreak(t *testing.T) {
// assert.Equal(6, sum) // assert.Equal(6, sum)
} }
// func TestPop(t *testing.T) { func TestPop(t *testing.T) {
// assert := internal.NewAssert(t, "TestPop") t.Parallel()
assert := internal.NewAssert(t, "TestSet_Pop")
// s := New[int]() s := New[int]()
// val, ok := s.Pop() val, ok := s.Pop()
// assert.Equal(0, val) assert.Equal(0, val)
// assert.Equal(false, ok) assert.Equal(false, ok)
// s.Add(1) s = New(1, 2, 3, 4, 5)
// s.Add(2) sl := s.ToSlice()
// s.Add(3)
// // s = New(1, 2, 3, 4, 5) val, ok = s.Pop()
assert.Equal(false, s.Contain(val))
assert.Equal(true, ok)
assert.Equal(len(sl)-1, s.Size())
// val, ok = s.Pop() var found bool
// assert.Equal(3, val)
// assert.Equal(true, ok) for _, v := range sl {
// } if v == val {
found = true
}
}
assert.Equal(true, found)
}
func TestSet_ToSlice(t *testing.T) { func TestSet_ToSlice(t *testing.T) {
t.Parallel() t.Parallel()