Skip to content

Commit

Permalink
List Insert method accept now one or more params
Browse files Browse the repository at this point in the history
In insert method on List you can now send slice of elements, not just one (like in previous version)
  • Loading branch information
jtomasevic committed Jul 24, 2022
1 parent e48e9a7 commit 2e7349a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
5 changes: 2 additions & 3 deletions collections/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,19 @@ func (list *List[T]) Add(element T) {
}

// Insert an element into the List[T] at the specified index.
func (list *List[T]) Insert(position int, element T) bool {
func (list *List[T]) Insert(position int, element ...T) bool {
if position > len(*list) || position < 0 {
return false
}
newList := *list
rightPart := append([]T{element}, newList[position:]...)
rightPart := append(element, newList[position:]...)
newList = append(newList[:position], rightPart...)
*list = newList
return true
}

// Remove the first occurrence of a specific object from the list
func (list *List[T]) Remove(element T) bool {
index := -1
exist, index := list.Exist(element)
if !exist {
return false
Expand Down
27 changes: 27 additions & 0 deletions collections/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,33 @@ func TestList_Integer(t *testing.T) {
res := list.Insert(8, forInsert)
require.Equal(t, len(list), 5)
require.Equal(t, res, false)

// insert array
list = initIntList()
arrForInsert := []int{11, 12, 13}
res = list.Insert(2, arrForInsert...)
require.True(t, res)
require.Equal(
t,
list,
List[int]{
1, 2, 11, 12, 13, 3, 4, 5,
},
)

// insert array
list = initIntList()
arrForInsert = []int{11, 12, 13}
res = list.Insert(0, arrForInsert...)
require.True(t, res)
require.Equal(
t,
list,
List[int]{
11, 12, 13, 1, 2, 3, 4, 5,
},
)

})
t.Run("Reverse", func(t *testing.T) {
list := initIntList()
Expand Down

0 comments on commit 2e7349a

Please sign in to comment.