Skip to content

Instantly share code, notes, and snippets.

@danielcodes
Created February 15, 2017 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielcodes/4b7a71dcc6f406448b9cd8de15967533 to your computer and use it in GitHub Desktop.
Save danielcodes/4b7a71dcc6f406448b9cd8de15967533 to your computer and use it in GitHub Desktop.
// library class, 2 methods
// find book details by ISBN
// find book by title
// can add more metadata later
function Book(title, author, isbn){
this.title = title;
this.author = author;
this.isbn = isbn;
}
var Library = (function(){
// book data is hardcoded, ideally it should come from an API, like goodreads?
var b1 = new Book('A Game of Thrones', 'George RR Martin', '0316769487');
var b2 = new Book('1984', 'George Orwell', '0316769123');
var b3 = new Book('The Catcher in the Rye', 'J. D. Salinger', '1236769487');
var books = [];
books.push(b1);
books.push(b2);
books.push(b3);
console.log('the books in the library are:');
console.log(books);
// method 1
// an O(n) solution, returns -1 if not found
// should do a check that the isbn passed is proper
var findByISBN = function(isbn){
var foundIdx = -1;
// step through list of books and try to find a match
for(var i=0; i<books.length; i++){
if(books[i].isbn == isbn){
foundIdx = i;
}
}
return foundIdx >= 0 ? books[foundIdx] : 'Book not found';
};
// method 2
// same as method1, but checks for a matching title instead
// since titles searchers are hit or miss
// an improvement can be providing recomendations
// based on similar titles if not found
var findByTitle = function(title){
var foundIdx = -1;
// step through list of books and try to find a match
for(var i=0; i<books.length; i++){
if(books[i].title == title){
foundIdx = i;
}
}
return foundIdx >= 0 ? books[foundIdx] : 'Book not found';
}
// API
return {
findByISBN: findByISBN,
findByTitle: findByTitle
};
// IIFE, returns the API
}());
console.log("\n\nFinding books by ISBN");
console.log(Library.findByISBN('0316769487'));
console.log(Library.findByISBN('1986198619'));
console.log("\n\nFinding books by title");
console.log(Library.findByTitle('1984'));
console.log(Library.findByTitle('1986'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment