From f6c9296952b062803a4991d3f97f76d61b0cc488 Mon Sep 17 00:00:00 2001 From: Grant Ammons Date: Fri, 3 Mar 2017 17:42:27 -0500 Subject: Add garbage collection feature * Add `todo gc`, which will delete all archived todos. * `NextId` will now take the first available id, rather than just the MaxId + 1. --- todolist/todo_list.go | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) (limited to 'todolist/todo_list.go') diff --git a/todolist/todo_list.go b/todolist/todo_list.go index d7e1f83..ea8ecbe 100644 --- a/todolist/todo_list.go +++ b/todolist/todo_list.go @@ -78,14 +78,32 @@ func (t *TodoList) Todos() []*Todo { return t.Data } -func (t *TodoList) NextId() int { +func (t *TodoList) MaxId() int { maxId := 0 for _, todo := range t.Data { if todo.Id > maxId { maxId = todo.Id } } - return maxId + 1 + return maxId +} + +func (t *TodoList) NextId() int { + var found bool + maxID := t.MaxId() + for i := 1; i <= maxID; i++ { + found = false + for _, todo := range t.Data { + if todo.Id == i { + found = true + break + } + } + if !found { + return i + } + } + return maxID + 1 } func (t *TodoList) FindById(id int) *Todo { @@ -96,3 +114,15 @@ func (t *TodoList) FindById(id int) *Todo { } return nil } + +func (t *TodoList) GarbageCollect() { + var toDelete []*Todo + for _, todo := range t.Data { + if todo.Archived { + toDelete = append(toDelete, todo) + } + } + for _, todo := range toDelete { + t.Delete(todo.Id) + } +} -- cgit v1.3