Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class LibraryCollection {
- constructor(capacity) {
- this.capacity = capacity;
- this.books = [];
- }
- addBook(bookName, bookAuthor) {
- if (this.books.length === this.capacity) {
- throw new Error('Not enough space in the collection.');
- }
- this.books.push({ bookName, bookAuthor, payed: false });
- return `The ${bookName}, with an author ${bookAuthor}, collect.`;
- }
- payBook(bookName) {
- let searchedBook = this.books.find((b) => b.bookName === bookName);
- if (!searchedBook) {
- throw new Error(`${bookName} is not in the collection.`);
- }
- if (searchedBook.payed) {
- throw new Error(`${bookName} has already been paid.`);
- }
- searchedBook.payed = true;
- return `${bookName} has been successfully paid.`;
- }
- removeBook(bookName) {
- let bookIdx = this.books.findIndex((b) => b.bookName === bookName);
- if (bookIdx === -1) {
- throw new Error("The book, you're looking for, is not found.");
- }
- if (!this.books[bookIdx].payed) {
- throw new Error(
- `${bookName} need to be paid before removing from the collection.`
- );
- }
- this.books.splice(bookIdx, 1);
- return `${bookName} remove from the collection.`;
- }
- getStatistics(bookAuthor) {
- let result = [];
- if (bookAuthor === undefined) {
- result.push(
- `The book collection has ${
- this.capacity - this.books.length
- } empty spots left.`
- );
- this.books
- .sort((a, b) => a.bookName.localeCompare(b.bookName))
- .forEach((b) =>
- result.push(
- `${b.bookName} == ${b.bookAuthor} - ${
- b.payed ? 'Has Paid' : 'Not Paid'
- }.`
- )
- );
- return result.join('\n');
- }
- let searchedBook = this.books.find((b) => b.bookAuthor === bookAuthor);
- if (!searchedBook) {
- throw new Error(`${bookAuthor} is not in the collection.`);
- }
- return `${searchedBook.bookName} == ${searchedBook.bookAuthor} - ${
- searchedBook.payed ? 'Has Paid' : 'Not Paid'
- }.`;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment