-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnotes.js
100 lines (81 loc) · 2.26 KB
/
notes.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const fs = require('fs')
const chalk = require('chalk')
const getNotes = () => {
return 'Your Notes...'
}
/**
*
* @param {string} title
* @param {string} body
*/
const addNotes = (title, body) => {
const existingData = loadNotes()
const isTitleExists = checkTitleExists(existingData, title)
debugger
if (!isTitleExists) {
existingData.push({
title: title,
body: body
})
saveNotes(existingData)
console.log(chalk.green.inverse('New Note added'))
} else {
console.log(chalk.red.inverse('Note title already taken'))
}
}
/**
*
* @param {string} title
*/
const removeNotes = (title) => {
const existingData = loadNotes()
const isTitleExists = checkTitleExists(existingData, title)
if (!isTitleExists) {
console.log(chalk.red.inverse('Note not found!'))
} else {
const updatedData = existingData.filter(note => note.title !== title)
console.log(chalk.green.inverse('Note Removed!'))
saveNotes(updatedData)
}
}
/**
* list a notes from datastore
*/
const listNotes = () => {
const existingData = loadNotes()
existingData.length === 0 ?
console.log(chalk.red.inverse('No Notes found')) :
existingData.forEach(element => console.log(chalk.green(element.title)))
}
/**
*
* @param {string} title
*/
const readNotes = (title) => {
const existingData = loadNotes()
const isTitleExists = checkTitleExists(existingData, title)
isTitleExists ?
console.log(chalk.green.bold(isTitleExists.title), ' ', isTitleExists.body) :
console.log(chalk.red.inverse('Note does not exist for this title'))
}
const checkTitleExists = (existingData, title) => existingData.find(note => note.title === title)
const saveNotes = (notes) => {
const dataString = JSON.stringify(notes)
fs.writeFileSync('notes.json', dataString)
}
const loadNotes = () => {
try {
const dataBuffer = fs.readFileSync('notes.json')
const dataJSON = dataBuffer.toString();
return JSON.parse(dataJSON);
} catch (error) {
return []
}
}
module.exports = {
getNotes: getNotes,
addNotes: addNotes,
removeNotes: removeNotes,
listNotes: listNotes,
readNotes: readNotes
};