-
Notifications
You must be signed in to change notification settings - Fork 1
/
todo.go
86 lines (72 loc) · 1.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
package main
import (
"encoding/json"
"fmt"
"math/rand"
"sync"
)
var (
todoList = []string{}
todoListMu sync.Mutex
)
func loadTodo(filename string) {
todoListMu.Lock()
defer todoListMu.Unlock()
if fileExists(filename) {
data := fileGetContents(filename)
checkErr(json.Unmarshal(data, &todoList))
}
}
func saveTodo(filename string) {
todoListMu.Lock()
defer todoListMu.Unlock()
data, err := json.Marshal(todoList)
checkErr(err)
filePutContents(filename, data)
}
func addTodo(item string) string {
todoListMu.Lock()
defer todoListMu.Unlock()
todoList = append(todoList, item)
return fmt.Sprintf(
"%s [%d thing%s to do]",
jmote["writing"][rand.Intn(len(jmote["writing"]))],
len(todoList),
func() string {
if len(todoList) == 1 {
return ""
}
return "s"
}(),
)
}
func removeTodo(idx int) string {
todoListMu.Lock()
defer todoListMu.Unlock()
if idx < 0 || idx >= len(todoList) {
return "invalid"
}
item := todoList[idx]
todoList = append(todoList[0:idx], todoList[idx+1:]...)
return fmt.Sprintf(
"✓ %s [%sthing%s left to do]",
item,
func() string {
if len(todoList) == 0 {
return "no"
}
return fmt.Sprintf("%d ", len(todoList))
}(),
func() string {
if len(todoList) <= 1 {
return ""
}
return "s"
}(),
)
}
func listTodo() []string {
todoListMu.Lock()
defer todoListMu.Unlock()
return todoList[:]
}