1import std/[tables, strutils, sequtils, algorithm]
2
3type
4 Priority = enum
5 pLow = "low"
6 pMedium = "medium"
7 pHigh = "high"
8
9 Task = object
10 id: int
11 title: string
12 priority: Priority
13 done: bool
14
15 TaskManager = object
16 tasks: seq[Task]
17 index: Table[int, int]
18 nextId: int
19
20proc newTaskManager(): TaskManager =
21 result.tasks = @[]
22 result.index = initTable[int, int]()
23 result.nextId = 1
24
25proc add(tm: var TaskManager, title: string,
26 priority = pMedium): int =
27 let id = tm.nextId
28 inc tm.nextId
29 let task = Task(
30 id: id,
31 title: title,
32 priority: priority,
33 done: false
34 )
35 tm.index[id] = tm.tasks.len
36 tm.tasks.add(task)
37 return id
38
39proc complete(tm: var TaskManager, id: int): bool =
40 if id notin tm.index:
41 return false
42 let idx = tm.index[id]
43 tm.tasks[idx].done = true
44 return true
45
46proc findByPriority(tm: TaskManager,
47 priority: Priority): seq[Task] =
48 tm.tasks.filterIt(
49 it.priority == priority and not it.done
50 )
51
52proc search(tm: TaskManager, query: string): seq[Task] =
53 let lower = query.toLowerAscii()
54 tm.tasks.filterIt(
55 lower in it.title.toLowerAscii()
56 )
57
58proc sortedByPriority(tm: TaskManager): seq[Task] =
59 result = tm.tasks.filterIt(not it.done)
60 result.sort do (a, b: Task) -> int:
61 cmp(ord(b.priority), ord(a.priority))
62
63template withTransaction(body: untyped) =
64 echo "BEGIN"
65 try:
66 body
67 echo "COMMIT"
68 except CatchableError:
69 echo "ROLLBACK"
70 raise
71
72proc summary(tm: TaskManager): Table[string, int] =
73 result = initTable[string, int]()
74 result["total"] = tm.tasks.len
75 result["done"] = tm.tasks.countIt(it.done)
76 result["pending"] = tm.tasks.countIt(not it.done)
77 for p in Priority:
78 result[$ p] = tm.tasks.countIt(it.priority == p)