aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Johnson <benbjohnson@yahoo.com>2022-12-26 16:01:27 -0700
committerGitHub <noreply@github.com>2022-12-26 16:01:27 -0700
commitec8f139ae65de6c8b4d94af3f449cd797bf597bf (patch)
tree923411e814dda63225ec752b1bfa960e8c9a2a25
parentMerge pull request #30 from laher/master (diff)
parentList: varargs for Append,Prepend,NewList (diff)
downloadpds-ec8f139ae65de6c8b4d94af3f449cd797bf597bf.tar.gz
pds-ec8f139ae65de6c8b4d94af3f449cd797bf597bf.tar.xz
Merge pull request #33 from laher/addmulti
List: varargs for Append,Prepend,NewList
-rw-r--r--immutable.go26
1 files changed, 19 insertions, 7 deletions
diff --git a/immutable.go b/immutable.go
index 2b91c9c..eefc573 100644
--- a/immutable.go
+++ b/immutable.go
@@ -62,10 +62,14 @@ type List[T any] struct {
}
// NewList returns a new empty instance of List.
-func NewList[T any]() *List[T] {
- return &List[T]{
+func NewList[T any](values ...T) *List[T] {
+ l := &List[T]{
root: &listLeafNode[T]{},
}
+ for _, value := range values {
+ l.append(value, true)
+ }
+ return l
}
// clone returns a copy of the list.
@@ -113,8 +117,12 @@ func (l *List[T]) set(index int, value T, mutable bool) *List[T] {
}
// Append returns a new list with value added to the end of the list.
-func (l *List[T]) Append(value T) *List[T] {
- return l.append(value, false)
+func (l *List[T]) Append(values ...T) *List[T] {
+ other := l.clone()
+ for _, value := range values {
+ other.append(value, true)
+ }
+ return other
}
func (l *List[T]) append(value T, mutable bool) *List[T] {
@@ -136,9 +144,13 @@ func (l *List[T]) append(value T, mutable bool) *List[T] {
return other
}
-// Prepend returns a new list with value added to the beginning of the list.
-func (l *List[T]) Prepend(value T) *List[T] {
- return l.prepend(value, false)
+// Prepend returns a new list with value(s) added to the beginning of the list.
+func (l *List[T]) Prepend(values ...T) *List[T] {
+ other := l.clone()
+ for i := len(values) - 1; i >= 0; i-- {
+ other.prepend(values[i], true)
+ }
+ return other
}
func (l *List[T]) prepend(value T, mutable bool) *List[T] {