-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.js
76 lines (62 loc) · 1.59 KB
/
tasks.js
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
const chalk = require('chalk');
const fs = require('fs');
//Add a task.
debugger
const addTask = (name) => {
const tasks = loadTasks();
const taskName = name.toString();
const duplicateTasks = tasks.filter ((task) => task.name === taskName
);
if (duplicateTasks.length === 0) {
tasks.push({
name: taskName
});
saveTasks(tasks);
console.log('new task added');
}
else {
console.log(chalk.red.inverse('Task has been added previously!'));
}
}
//Saves tasks.
const saveTasks = (tasks) => {
const tasksJSON = JSON.stringify(tasks);
fs.writeFileSync('tasks.json', tasksJSON);
};
//Load existing tasks.
const loadTasks = () => {
try {
const taskBuffer = fs.readFileSync('tasks.json');
const tasks = taskBuffer.toString();
return JSON.parse(tasks);
} catch (e) {
return [];
}
}
//Delete a task.
const deleteTask = (name) => {
const tasks = loadTasks();
const remainingTasks = tasks.filter ((task) => {
return task.name !== name;
});
if (remainingTasks.length === tasks.length) {
console.log(chalk.inverse.red('task doesn\'t exist!'));
} else {
saveTasks(remainingTasks);
console.log('task removed');
}
}
//List incomplete tasks
const listTasks = () => {
const tasks = loadTasks();
tasks.forEach(task => {
console.log(task.name);
});
}
module.exports = {
addTask: addTask,
loadTasks: loadTasks,
saveTasks: saveTasks,
deleteTask: deleteTask,
listTasks: listTasks,
};