Skip to content

Instantly share code, notes, and snippets.

@Elergy
Last active March 18, 2020 22:40
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 Elergy/f79952ffa36fbf84877c7599221127cb to your computer and use it in GitHub Desktop.
Save Elergy/f79952ffa36fbf84877c7599221127cb to your computer and use it in GitHub Desktop.
addBook (author, title) {
const book = this._findExisting(author, title);
if (book) {
book.total += 1;
book.available += 1;
} else {
this._books.push({
info: {
author: author,
title: title,
},
total: 1,
available: 1
});
}
}
const book = this._findExisting(author, title);
if (!book || !book.available) {
return null;
}
class Library {
constructor () {
this._books = [];
}
addBook (author, title) {
const book = this._findExisting(author, title);
if (book) {
book.total += 1;
book.available += 1;
} else {
this._books.push({
author: author,
title: title,
total: 1,
available: 1
});
}
}
takeBook (author, title) {
const book = this._findExisting(author, title);
if (!book || !book.available) {
return null;
}
book.available -= 1;
return book;
}
_findExisting (author, title) { ... }
}
test(
'.takeBook should return return `null` ' +
'if we have the book in the library, ' +
'but there are no available copies', () => {
// prepare
const library = new Library();
library._books = [
{
author: 'King', title: 'It',
available: 0, total: 1
},
{
author: 'King', title: 'Carrie',
available: 1, total: 1
},
{
author: 'Orwell', title: '1984',
available: 1, total: 1
}
];
// act
const book = library.takeBook('King', 'It');
// verify
isNull(bookId)
}
);
library._books = [
{
author: 'King', title: 'It',
available: 0, total: 1 // no avaiable copies
},
{
author: 'King', title: 'Carrie',
available: 1, total: 1
},
{
author: 'Orwell', title: '1984',
available: 1, total: 1
}
];
test(
'.takeBook should return return `null` ' +
'if we have the book in the library, ' +
'but there are no available copies', () => {
// prepare
const library = new Library();
library.addBook('King', 'It');
library.addBook('King', 'Carrie');
library.addBook('Orwell', '1984');
// remove one available copy of "It"
library.takeBook('King', 'It');
// act
const book = library.takeBook('King', 'It');
// verify
isNull(bookId)
}
);
takeBook (author, title) {
const book = this._findExisting(author, title);
if (!book) {
return null;
}
book.available -= 1;
return book;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment