Last active
August 29, 2015 14:22
-
-
Save searchs/498bebb78d857a746ad1 to your computer and use it in GitHub Desktop.
Contact module of Address book
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Contact = {}; | |
Contact.parseName = function(str) { | |
return str.split(',')[0].trim() | |
}; | |
Contact.parseNumber = function(str) { | |
return str.split(',')[1].trim() | |
}; | |
Contact.createContact = function(str) { | |
var contact = { | |
name: this.parseName(str), | |
number: this.parseNumber(str) | |
}; | |
return contact | |
}; | |
Contact.loadContacts = function(done) { | |
var jsonfile = require('jsonfile') | |
jsonfile.readFile('data.json', function(err, data) { | |
done(err, data) | |
}) | |
}; | |
Contact.saveContacts = function(contacts, done) { | |
var jsonfile = require('jsonfile') | |
jsonfile.writeFile('data.json', contacts, done) | |
}; | |
Contact.saveContact = function(contact, done) { | |
var _this = this | |
this.loadContacts(function(err, contacts) { | |
if (err) { | |
return done(err) | |
} | |
contacts.push(contact) | |
_this.saveContacts(contacts, done) | |
}) | |
}; | |
Contact.findContacts = function(name, done) { | |
var foundContacts = [] | |
this.loadContacts(function(err, contacts) { | |
if (err) { | |
return done(err) | |
} | |
console.log("Contacts:__" + contacts.toString()); | |
foundContacts = contacts.filter(function(person) { | |
return (person.name === name) | |
}); | |
done(err, foundContacts); | |
}); | |
}; | |
module.exports = Contact; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment