feature: added array list

master
amorozov 2024-06-19 21:58:07 +03:00
parent 0316759f1a
commit 9212b24d14
3 changed files with 143 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package array_list
func NewArrayList[T any]() *ArrayList[T] {
return &ArrayList[T]{
content: make([]T, 0, 10),
size: 0,
}
}

View File

@ -0,0 +1,129 @@
package array_list
import (
"errors"
"fmt"
)
func (self *ArrayList[T]) Add(element T) {
if len(self.content) <= self.size {
self.content = append(self.content, element)
} else {
self.content[self.size] = element
}
self.size++
}
func (self *ArrayList[T]) Remove(element T) {
indexFromMove := -1
for index, value := range self.content {
if any(value) == any(element) {
indexFromMove = index + 1
break
}
}
contentSize := len(self.content)
if indexFromMove >= 0 {
for i := indexFromMove; i < contentSize; i++ {
self.content[i-1] = self.content[i]
}
self.size--
}
}
func (self *ArrayList[T]) Get(index int) T {
if index < 0 {
panic(any(errors.New(fmt.Sprintf("Negative list index %d", index))))
}
if index >= self.size {
panic(any(errors.New(fmt.Sprintf("Index %d bigger (or equal?) than list size %d", index, self.size))))
}
return self.content[index]
}
func (self *ArrayList[T]) IndexOf(value T) int {
if self.size == 0 {
return -1
}
for index, val := range self.content {
if any(val) == any(value) {
return index
}
}
return -1
}
func (self *ArrayList[T]) Contains(value T) bool {
return self.IndexOf(value) >= 0
}
func (self *ArrayList[T]) None(test func(T) bool) bool {
return !self.Any(test)
}
func (self *ArrayList[T]) AddAll(list *ArrayList[T]) {
list.ForEach(func(t T) {
self.Add(t)
})
}
func (self *ArrayList[T]) Any(test func(T) bool) bool {
for index, value := range self.content {
if index >= self.size {
return false
}
if test(value) {
return true
}
}
return false
}
func (self *ArrayList[T]) ForEach(fun func(T)) {
for index, value := range self.content {
if index >= self.size {
return
}
fun(value)
}
}
func (self *ArrayList[T]) ForEachBreakable(fun func(T, *bool)) {
needsBreak := false
for index, value := range self.content {
if index >= self.size {
return
}
if needsBreak {
break
}
fun(value, &needsBreak)
}
}
func (self *ArrayList[T]) Size() int {
return self.size
}
func (self *ArrayList[T]) IsEmpty() bool {
return self.Size() <= 0
}
func (self *ArrayList[T]) String() string {
return fmt.Sprintf("%v", self.content)
}

View File

@ -0,0 +1,6 @@
package array_list
type ArrayList[T any] struct {
content []T
size int
}