From e89429a93ce6029507687b96f5d231ad7791243f Mon Sep 17 00:00:00 2001 From: amorozov Date: Thu, 20 Jun 2024 13:33:05 +0300 Subject: [PATCH] feature: added RemoveIf and RemoveByIndex functions into array list --- .../array_list/array_list_methods.go | 27 ++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/pkg/collections/array_list/array_list_methods.go b/pkg/collections/array_list/array_list_methods.go index 31eecf2..c701b22 100644 --- a/pkg/collections/array_list/array_list_methods.go +++ b/pkg/collections/array_list/array_list_methods.go @@ -15,6 +15,24 @@ func (self *ArrayList[T]) Add(element T) { self.size++ } +func (self *ArrayList[T]) RemoveIf(filter func(T) bool) { + index := 0 + for { + if index >= self.size { + break + } + + element := self.content[index] + shouldRemove := filter(element) + + if shouldRemove { + self.RemoveByIndex(index) + } else { + index++ + } + } +} + func (self *ArrayList[T]) Remove(element T) { indexFromMove := -1 for index, value := range self.content { @@ -25,11 +43,14 @@ func (self *ArrayList[T]) Remove(element T) { } } + self.RemoveByIndex(indexFromMove) +} + +func (self *ArrayList[T]) RemoveByIndex(index int) { contentSize := len(self.content) - if indexFromMove >= 0 { - - for i := indexFromMove; i < contentSize; i++ { + if index >= 0 { + for i := index; i < contentSize; i++ { self.content[i-1] = self.content[i] }