Skip to content

Commit

Permalink
Adding function to delete items from list by content or index
Browse files Browse the repository at this point in the history
  • Loading branch information
jaavier committed Nov 5, 2022
1 parent 8e289a6 commit 3d77cec
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
30 changes: 30 additions & 0 deletions lists.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,4 +154,34 @@ func DeleteList(listName string) error {
}
}
return fmt.Errorf("list '%s' doesn't exist", listName)
}

func DeleteItemByContent(listName string, item string) bool {
var list, err = GetList(listName)
if err != nil {
return false
}
var newList []string
for _, value := range list {
if value != item {
newList = append(newList, value)
}
}
lists[listName] = newList
return true
}

func DeleteItemByIndex(listName string, index int) bool {
var list, err = GetList(listName)
if err != nil {
return false
}
var newList []string
for i, value := range list {
if i != index {
newList = append(newList, value)
}
}
lists[listName] = newList
return true
}
28 changes: 28 additions & 0 deletions tests/lists_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,32 @@ func TestLists(t *testing.T) {
t.Errorf("error: %v", err)
}
})

t.Run("Delete item from list by content", func(t *testing.T) {
var listName string = "tmp-list-with-item"
var newItem string = "delete-me"
sider.RPush(listName, newItem)
if sider.DeleteItemByContent(listName, newItem) == false {
t.Errorf("Error deleting item: %v", newItem)
}
if result, _ := sider.GetList(listName); len(result) != 0 {
t.Errorf("[2] Error deleting item: %s", newItem)
}
})

t.Run("Delete item from list by index", func(t *testing.T) {
var listName string = "delete-list-by-index"
var newItem string = "delete-item"
sider.RPush(listName, newItem)
if index, err := sider.IndexOf(listName, newItem); err != nil {
t.Errorf("error finding index for item: %s", newItem)
} else {
if sider.DeleteItemByIndex(listName, index) == false {
t.Errorf("[2] Error deleting item by index: %s", newItem)
}
if result, _ := sider.GetList(listName); len(result) != 0 {
t.Errorf("[3] Error deleting item: %s", newItem)
}
}
})
}

0 comments on commit 3d77cec

Please sign in to comment.