viligen

libraryCollection

Jun 14th, 2022
881
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class LibraryCollection {
  2.     constructor(capacity) {
  3.         this.capacity = capacity;
  4.         this.books = [];
  5.     }
  6.     addBook(bookName, bookAuthor) {
  7.         if (this.books.length === this.capacity) {
  8.             throw new Error('Not enough space in the collection.');
  9.         }
  10.         this.books.push({ bookName, bookAuthor, payed: false });
  11.         return `The ${bookName}, with an author ${bookAuthor}, collect.`;
  12.     }
  13.     payBook(bookName) {
  14.         let searchedBook = this.books.find((b) => b.bookName === bookName);
  15.         if (!searchedBook) {
  16.             throw new Error(`${bookName} is not in the collection.`);
  17.         }
  18.         if (searchedBook.payed) {
  19.             throw new Error(`${bookName} has already been paid.`);
  20.         }
  21.         searchedBook.payed = true;
  22.         return `${bookName} has been successfully paid.`;
  23.     }
  24.     removeBook(bookName) {
  25.         let bookIdx = this.books.findIndex((b) => b.bookName === bookName);
  26.         if (bookIdx === -1) {
  27.             throw new Error("The book, you're looking for, is not found.");
  28.         }
  29.         if (!this.books[bookIdx].payed) {
  30.             throw new Error(
  31.                 `${bookName} need to be paid before removing from the collection.`
  32.             );
  33.         }
  34.         this.books.splice(bookIdx, 1);
  35.         return `${bookName} remove from the collection.`;
  36.     }
  37.     getStatistics(bookAuthor) {
  38.         let result = [];
  39.         if (bookAuthor === undefined) {
  40.             result.push(
  41.                 `The book collection has ${
  42.                     this.capacity - this.books.length
  43.                 } empty spots left.`
  44.             );
  45.             this.books
  46.                 .sort((a, b) => a.bookName.localeCompare(b.bookName))
  47.                 .forEach((b) =>
  48.                     result.push(
  49.                         `${b.bookName} == ${b.bookAuthor} - ${
  50.                             b.payed ? 'Has Paid' : 'Not Paid'
  51.                         }.`
  52.                     )
  53.                 );
  54.             return result.join('\n');
  55.         }
  56.         let searchedBook = this.books.find((b) => b.bookAuthor === bookAuthor);
  57.         if (!searchedBook) {
  58.             throw new Error(`${bookAuthor} is not in the collection.`);
  59.         }
  60.         return `${searchedBook.bookName} == ${searchedBook.bookAuthor} - ${
  61.             searchedBook.payed ? 'Has Paid' : 'Not Paid'
  62.         }.`;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment