diff --git a/ds/list.go b/ds/list.go index 8d243d797..1f6c071dc 100644 --- a/ds/list.go +++ b/ds/list.go @@ -60,12 +60,15 @@ type List[T any] interface { // RangeReverse executes the given callback for the value of each element in the List in reverse order. RangeReverse(callback func(value T)) + // Values returns a slice of all values in the List. + Values() []T + // Len returns the number of elements in the List. Len() int } -// NewList creates a new List (the optional lockFree parameter can be set to true to create a List that is not thread -// safe). +// NewList creates a new List (the optional lockFree parameter can be set to true to create a List that is not +// thread-safe). func NewList[T any](lockFree ...bool) List[T] { if len(lockFree) > 0 && lockFree[0] { return newList[T]() diff --git a/ds/list_impl.go b/ds/list_impl.go index b9811e7c2..5648f0888 100644 --- a/ds/list_impl.go +++ b/ds/list_impl.go @@ -239,6 +239,17 @@ func (l *list[T]) RangeReverse(callback func(value T)) { } } +// Values returns a slice of all values in the List. +func (l *list[T]) Values() []T { + values := make([]T, 0) + + l.Range(func(value T) { + values = append(values, value) + }) + + return values +} + // Len returns the number of elements in the List. func (l *list[T]) Len() int { return l.len } @@ -458,6 +469,14 @@ func (t *threadSafeList[T]) RangeReverse(callback func(value T)) { t.list.RangeReverse(callback) } +// Values returns a slice of all values in the List. +func (t *threadSafeList[T]) Values() []T { + t.mutex.RLock() + defer t.mutex.RUnlock() + + return t.list.Values() +} + // Len returns the number of elements in the List. func (t *threadSafeList[T]) Len() int { t.mutex.RLock()