Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Values() added to Array #4

Merged
merged 1 commit into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ A thread-safe array with a fixed size.
- `(*Array[T]) Clear()` - Clears all elements from the array.
- `(*Array[T]) Insert(index int, value T) bool` - Inserts a value at the specified index.
- `(*Array[T]) Copy() *Array[T]` - Returns a copy of the array.
- `(*Array[T]) Values() []T` - Returns a slice of all elements in the array.
- `(*Array[T]) Length() int` - Returns the length of the array.

#### Example
Expand Down
12 changes: 12 additions & 0 deletions array.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ func (a *Array[T]) Length() int {
return len(a.data)
}

// Values returns a slice of all elements in the array.
// Example:
//
// values := arr.Values()
func (a *Array[T]) Values() []T {
a.mu.RLock()
defer a.mu.RUnlock()
dataCopy := make([]T, len(a.data))
copy(dataCopy, a.data)
return dataCopy
}

// Append appends a value to the array.
// Example:
//
Expand Down
20 changes: 20 additions & 0 deletions array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,23 @@ func TestArrayCopy(t *testing.T) {
assert.Equal(t, origValue, copyValue)
}
}
func TestArrayValues(t *testing.T) {
arr := NewArray[int](10)

// Set values in the array
for i := 0; i < arr.Length(); i++ {
arr.Set(i, i*10)
}

// Get all values from the array
values := arr.Values()

// Check the length of the values slice
assert.Equal(t, arr.Length(), len(values))

// Check each value
for i, v := range values {
expectedValue, _ := arr.Get(i)
assert.Equal(t, expectedValue, v)
}
}
Loading