-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.go
102 lines (79 loc) · 1.73 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"errors"
"fmt"
"os"
"strconv"
"time"
"github.com/aquasecurity/table"
)
type Todo struct {
Title string
Completed bool
CreatedAt time.Time
CompletedAt *time.Time
}
type Todos []Todo
func (todos *Todos) add(title string) {
todo := Todo{
Title: title,
Completed: false,
CreatedAt: time.Now(),
CompletedAt: nil,
}
*todos = append(*todos, todo)
}
func (todos *Todos) validateIndex(index int) error {
if index < 0 || index >= len(*todos) {
err := errors.New("Invalid index")
fmt.Println(err)
return err
}
return nil
}
func (todos *Todos) delete(index int) error {
t := *todos
if err := t.validateIndex(index); err != nil {
return err
}
*todos = append(t[:index], t[index+1:]...)
return nil
}
func (todos *Todos) toggle(index int) error {
t := *todos
if err := t.validateIndex(index); err != nil {
return err
}
isCompleted := t[index].Completed
if !isCompleted {
completedTime := time.Now()
t[index].CompletedAt = &completedTime
}
t[index].Completed = !isCompleted
return nil
}
func (todos *Todos) edit(index int, title string) error {
t := *todos
if err := t.validateIndex(index); err != nil {
return err
}
t[index].Title = title
return nil
}
func (todos *Todos) print() {
table := table.New(os.Stdout)
table.SetRowLines(false)
table.SetHeaders("#", "Title", "Completed", "Created At", "Completed At")
for index, todo := range *todos {
completed := "❌"
completedAt := ""
if todo.Completed {
completed = "✅"
if todo.CompletedAt != nil {
completedAt = todo.CompletedAt.Format(time.RFC1123)
}
}
table.AddRow(strconv.Itoa(index), todo.Title, completed, todo.CreatedAt.Format(time.RFC1123), completedAt)
}
table.Render()
}