-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.go
102 lines (85 loc) · 1.91 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,
CompletedAt: nil,
CreatedAt: time.Now(),
}
*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 {
todo := *todos
if err := todo.validateIndex(index); err != nil {
return err
}
*todos = append(todo[:index], todo[index+1:]...)
return nil
}
func (todos *Todos) Toggle(index int) error {
todo := *todos
if err := todo.validateIndex(index); err != nil {
return err
}
isCompleted := todo[index].Completed
if !isCompleted {
completionTime := time.Now()
todo[index].CompletedAt = &completionTime
// added by me
todo[index].Completed = true
// and below else also added by me
} else {
todo[index].Completed = false
todo[index].CompletedAt = nil
}
// todo[index].Completed = !isCompleted
return nil
}
func (todos *Todos) Edit(index int, title string) error {
todo := *todos
if err := todo.validateIndex(index); err != nil {
return err
}
todo[index].Title = title
return nil
}
func (todos *Todos) Print() {
table := table.New(os.Stdout)
table.SetRowLines(false)
table.SetHeaders("#", "Title", "Completed", "CreatedAt", "CompletedAt")
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()
}