-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtodo.go
More file actions
101 lines (80 loc) · 2.07 KB
/
todo.go
File metadata and controls
101 lines (80 loc) · 2.07 KB
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
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 {
t := *todos // Mengambil slice asli yang ditunjuk oleh pointer todos
if err := t.validateIndex(index); err != nil {
return err // Jika index tidak valid, kembalikan error
}
// Menghapus item pada index yang diberikan
*todos = append(t[:index], t[index+1:]...)
return nil // Tidak ada error, berarti sukses
}
func (todos *Todos) toggle(index int) error {
t := *todos// Mengambil slice asli yang ditunjuk oleh pointer todos
if err := t.validateIndex(index); err != nil {
return err // Jika index tidak valid, kembalikan error
}
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// Mengambil slice asli yang ditunjuk oleh pointer todos
if err := t.validateIndex(index); err != nil {
return err // Jika index tidak valid, kembalikan error
}
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, t := range *todos {
completed := "❌"
completedAt := ""
if t.Completed {
completed = "✅"
if t.CompletedAt != nil {
completedAt = t.CompletedAt.Format(time.RFC1123)
}
}
table.AddRow(strconv.Itoa(index), t.Title, completed,t.CreatedAt.Format(time.RFC1123), completedAt )
}
table.Render()
}