Skip to content

Instantly share code, notes, and snippets.

@Elergy

Elergy/add-book-changed.js

Last active Mar 18, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.