3.10 Refactoring for Reusability

Last time we thoroughly updated our add-notes function. Recall the add-notes function is defined as follows

var addNote = (title, body) => {
var notes=[];
var note = {
title, // same as title: title
body
};
try {
var notesString = fs.readFileSync('notes-data.json'); // files may be non-existent
notes = JSON.parse(notesString); // files may be invalid
} catch (e) {
}
var duplicateNotes = notes.filter((note) => {
return note.title === title;
});
if (duplicateNotes.length === 0) {
notes.push(note);
fs.writeFileSync('notes-data.json', JSON.stringify(notes));
}
};

We could see high reusability of some chunk of codes when we write other notes manipulations.
Now let’s factor them in order to reuse them.

var fetchNotes = () => {
try {
var notesString = fs.readFileSync('notes-data.json');
notes = JSON.parse(notesString);
return notes;
} catch (e) {
return [];
}
};
var saveNotes = (notes) => {
fs.writeFileSync('notes-data.json', JSON.stringify(notes));
};
var addNote = (title, body) => {
var notes=fetchNotes;
var note = { title, body };
var duplicateNotes = notes.filter((note) => return note.title === title);
if (duplicateNotes.length === 0) {
notes.push(note);
saveNotes(notes);
}
};

Remarks:

Let’s make our app more responsive! Add a return value for add-notes so that when the front-most part of the app that calls it would be able to get a return value so to print responsive information accordingly.

var addNote = (title, body) => {
var notes = fetchNotes();
var note = { title, body };
var duplicateNotes = notes.filter((note) => note.title === title);
if (duplicateNotes.length === 0) {
notes.push(note);
saveNotes(notes);
return note;
}
};

Remarks:

In our front-most part, we do the following updates:

if (command === 'add') {
var note = notes.addNote(argv.title, argv.body);
if (note) {
console.log('note created');
console.log('--');
console.log(`Title: ${note.title}`);
console.log(`Body: ${note.body}`);
} else {
console.log('note title taken')
}

A little demo here:

jude@jude-ThinkPad-S5:/media/jude/Jude 1TB/nodejs/notes-app$ node app.js add --title="cs245 a7" --body="do it now"
note created
--
Title: cs245 a7
Body: do it now
jude@jude-ThinkPad-S5:/media/jude/Jude 1TB/nodejs/notes-app$ node app.js add --title="cs245 a7" --body="do it later"
note title taken