Skip to content

Commit

Permalink
added Values method to List
Browse files Browse the repository at this point in the history
  • Loading branch information
hmoog committed Oct 16, 2023
1 parent 4eebbad commit 03b59e3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
7 changes: 5 additions & 2 deletions ds/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]()
Expand Down
19 changes: 19 additions & 0 deletions ds/list_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 03b59e3

Please sign in to comment.