diff --git a/datastructure/list/list.go b/datastructure/list/list.go index 2c87e33..0335adb 100644 --- a/datastructure/list/list.go +++ b/datastructure/list/list.go @@ -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 diff --git a/datastructure/list/list_test.go b/datastructure/list/list_test.go index d3636c3..b234e48 100644 --- a/datastructure/list/list_test.go +++ b/datastructure/list/list_test.go @@ -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) +} diff --git a/docs/datastructure/list.md b/docs/datastructure/list.md index fd130d5..483111e 100644 --- a/docs/datastructure/list.md +++ b/docs/datastructure/list.md @@ -47,6 +47,7 @@ import ( - [Union](#Union) - [Intersection](#Intersection) - [SubList](#SubList) +- [DeleteIf](#DeleteIf)
@@ -820,4 +821,33 @@ func main() { fmt.Println(l.SubList(2, 5)) // []int{3, 4, 5} } -``` \ No newline at end of file +``` + + + + +### DeleteIf +DeleteIf delete all satisfying f(data[i]), returns count of removed elements
+ +Signature: + +```go +func (l *List[T]) DeleteIf(f func(T) bool) int +``` +Example: + +```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} +} +```