-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.go
73 lines (57 loc) · 1.29 KB
/
todo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"errors"
"fmt"
)
type Todo struct {
text string
id int
done bool
}
type TodoRepo []Todo
func (tr TodoRepo) String() (todos string) {
for _, todo := range tr {
done := ""
if todo.done {
done = "\u2713"
}
todos += fmt.Sprintf("%v - %v %v\n", todo.id, todo.text, done)
}
return todos
}
func AppendTodo(tr TodoRepo, todo Todo) (TodoRepo, int) {
tr = append(tr, todo)
return tr, todo.id + 1
}
func EditTodoText(tr TodoRepo, todoID int, updatedText string) (error, TodoRepo, Todo) {
err, index := findIndex(tr, todoID)
if err != nil {
return err, tr, Todo{}
}
tr[index].text = updatedText
return nil, tr, tr[index]
}
func ToggleDone(tr TodoRepo, todoID int) (TodoRepo, Todo, error) {
err, index := findIndex(tr, todoID)
if err != nil {
return tr, Todo{}, err
}
tr[index].done = !tr[index].done
return tr, tr[index], err
}
func RemoveTodo(tr TodoRepo, todoID int) (error, TodoRepo) {
err, selectedIndexID := findIndex(tr, todoID)
if err != nil {
return err, tr
}
tr = append(tr[:selectedIndexID], tr[selectedIndexID+1:]...)
return nil, tr
}
func findIndex(tr TodoRepo, todoID int) (error, int) {
for i, t := range tr {
if t.id == todoID {
return nil, i
}
}
return errors.New(fmt.Sprint("Did not find todo with id: ", todoID)), -1
}