-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.go
113 lines (94 loc) · 2.37 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
103
104
105
106
107
108
109
110
111
112
113
package todo
import (
"encoding/json"
"errors"
"fmt"
"os"
"time"
)
// todo is a struct containing information about
// a particular todo item.
type todo struct {
Task string
Done bool
CreatedAt time.Time
CompletedAt time.Time
}
// TodoList is a custom type with the underlying []todo data type.
// It contains various methods for creating and managing todos.
type TodoList []todo
// Add creates a new todo item and appends it to the list.
func (t *TodoList) Add(task string) {
item := todo{
Task: task,
CreatedAt: time.Now(),
Done: false,
}
*t = append(*t, item)
}
// Complete marks a todo item as completed.
//
// It sets Done field to true and CompletedAt field to the current time
func (t *TodoList) Complete(pos int) error {
todoList := *t
// Check if pos is within the range of todo list.
if pos <= 0 || pos > len(todoList) {
return fmt.Errorf("item %d does not exist", pos)
}
// Adjusting for 0-based index.
todoList[pos-1].Done = true
todoList[pos-1].CompletedAt = time.Now()
return nil
}
// Delete a todo item from the todo list based on the
// provided position in the list.
func (t *TodoList) Delete(pos int) error {
todoList := *t
// Check if pos is within the range of todo list.
if pos <= 0 || pos > len(todoList) {
return fmt.Errorf("item %d does not exist", pos)
}
// Adjusting for 0-based index.
*t = append(todoList[:pos-1], todoList[pos:]...)
return nil
}
// Save encodes the TodoList as JSON and then saves it
// using the provided file name into the current working directory.
func (t *TodoList) Save(filename string) error {
js, err := json.MarshalIndent(t, "", "\t")
if err != nil {
return err
}
return os.WriteFile(filename, js, 0644)
}
// Get opens the provided file name, decodes the JSON data
// and parses it into the TodoList.
func (t *TodoList) Get(filename string) error {
file, err := os.ReadFile(filename)
if err != nil {
switch {
case errors.Is(err, os.ErrNotExist):
return nil
default:
return err
}
}
if len(file) == 0 {
return nil
}
return json.Unmarshal(file, t)
}
// String prints out a formatted list of to-do items.
//
// It implements the fmt.Stringer interface.
func (t *TodoList) String() string {
formatted := ""
for k, t := range *t {
prefix := " "
if t.Done {
prefix = "X "
}
formatted += fmt.Sprintf("%s%d: %s\n", prefix, k+1, t.Task)
}
return formatted
}