Skip to content

Commit

Permalink
list: add DeleteIf method (#50)
Browse files Browse the repository at this point in the history
DeleteIf delete all satisfying f(data[i]), returns count of removed elements
  • Loading branch information
donutloop authored Jul 23, 2022
1 parent 0299c45 commit 3d7600a
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 1 deletion.
25 changes: 25 additions & 0 deletions datastructure/list/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,31 @@ func (l *List[T]) DeleteAt(index int) {
l.data = data
}

// DeleteIf delete all satisfying f(data[i]), returns count of removed elements
func (l *List[T]) DeleteIf(f func(T) bool) int {
data := l.data
size := len(data)

var c int
for index := 0; index < len(data); index++ {
if !f(data[index]) {
continue
}
if index == size-1 {
data = append(data[:index])
} else {
data = append(data[:index], data[index+1:]...)
index--
}
c++
}

if c > 0 {
l.data = data
}
return c
}

// UpdateAt update value of list at index, index shoud between 0 and list size -1
func (l *List[T]) UpdateAt(index int, value T) {
data := l.data
Expand Down
14 changes: 14 additions & 0 deletions datastructure/list/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,17 @@ func BenchmarkSubSlice(b *testing.B) {
list.SubList(2, 5)
}
}

func TestDeleteIf(t *testing.T) {
assert := internal.NewAssert(t, "TestDeleteIf")

list := NewList([]int{1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1})

count := list.DeleteIf(func(a int) bool { return a == 1 })
assert.Equal([]int{2, 3, 4}, list.Data())
assert.Equal(12, count)

count = list.DeleteIf(func(a int) bool { return a == 5 })
assert.Equal([]int{2, 3, 4}, list.Data())
assert.Equal(0, count)
}
32 changes: 31 additions & 1 deletion docs/datastructure/list.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import (
- [Union](#Union)
- [Intersection](#Intersection)
- [SubList](#SubList)
- [DeleteIf](#DeleteIf)

<div STYLE="page-break-after: always;"></div>

Expand Down Expand Up @@ -820,4 +821,33 @@ func main() {

fmt.Println(l.SubList(2, 5)) // []int{3, 4, 5}
}
```
```




### <span id="DeleteIf">DeleteIf</span>
<p>DeleteIf delete all satisfying f(data[i]), returns count of removed elements</p>

<b>Signature:</b>

```go
func (l *List[T]) DeleteIf(f func(T) bool) int
```
<b>Example:</b>

```go
package main

import (
"fmt"
list "github.com/duke-git/lancet/v2/datastructure/list"
)

func main() {
l := list.NewList([]int{1, 1, 1, 1, 2, 3, 1, 1, 4, 1, 1, 1, 1, 1, 1})

fmt.Println(l.DeleteIf(func(a int) bool { return a == 1 })) // 12
fmt.Println(l.Data()) // []int{2, 3, 4}
}
```

0 comments on commit 3d7600a

Please sign in to comment.