3.12 Reading Notes and Reusability

Tasks for this lesson:

  1. Complete getNote in both app.js part and notes.js part.
  2. Refactor code

Implementing getNote

In app.js

...
} else if (command == 'read') {
var note = notes.getNote(argv.title);
if (note) {
console.log("note found");
console.log("--");
console.log(`Title: ${note.title}`);
console.log("Body: ${note.body}");
} else {
console.log("note not found");
}
}
...

In notes.js

var getNote = (title) => {
var notes = fetchNotes();
var filteredNotes = notes.filter((note) => note.title === title);
return filteredNotes[0];
};

Refactor to Solve DRY

DRY : Don’t repeat yourself.

We found that

console.log('--');
console.log(`Title: ${note.title}`);
console.log(`Body: ${note.body}`);

The above chunk of code has been repeated a lot of times.
We are going to make a function called logNote in notes.js. The function is defined as follows:

var logNote = (note) => {
console.log('--');
console.log(`Title: ${note.title}`);
console.log(`Body: ${note.body}`);
}

Two places have been relaxed:

if (command === 'add') {
var note = notes.addNote(argv.title, argv.body);
if (note) {
console.log('Note created');
notes.logNote(note);
} else {
console.log('Note title taken');
}

as well as

} else if (command === 'read') {
var note = notes.getNote(argv.title);
if (note) {
console.log("note found");
notes.logNote(note);
} else {
console.log("note not found");
}