Advertisement
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.");
- } else {
- this.books.push({
- bookName,
- bookAuthor,
- payed: false,
- });
- return `The ${bookName}, with an author ${bookAuthor}, collect.`;
- }
- }
- payBook(bookName) {
- let book = this.books.find((b) => b.bookName == bookName);
- if (!book) {
- throw new Error(`${bookName} is not in the collection.`);
- }
- // check if book is alredy paid
- if (book.payed) {
- throw new Error(`${bookName} has already been paid.`);
- }
- book.payed = true;
- return `${bookName} has been successfully paid.`;
- }
- removeBook(bookName) {
- let book = this.books.find((b) => b.bookName == bookName);
- if (!book) {
- throw new Error("The book, you're looking for, is not found.");
- }
- if (book.payed == false) {
- throw new Error(
- `${bookName} need to be paid before removing from the collection.`
- );
- } else {
- for (const b of this.books) {
- delete book.bookName;
- return `${bookName} remove from the collection.`;
- }
- }
- }
- getStatistics(bookAuthor) {
- let isPayed;
- if (bookAuthor) {
- if (!this.books.find(b => b.bookAuthor == bookAuthor)) {
- throw new Error(`${bookAuthor} is not in the collection.`);
- }
- // you need to return array of all books by given author
- const booksByAuthor = [];
- this.books.map(b => b.bookAuthor == bookAuthor);
- for (const book of this.books) {
- if (book.payed) {
- isPayed = "Has Paid";
- } else {
- isPayed = "Not Paid";
- }
- booksByAuthor.push(
- `${book.bookName} == ${book.bookAuthor} - ${isPayed}.`
- );
- }
- return booksByAuthor.join("\n");
- } else {
- let resultArr = [
- `The book collection has ${this.capacity - this.books.length
- } empty spots left.`,
- ];
- let sortedNames = this.books.sort((a, b) =>
- a.bookName.localeCompare(b.bookName)
- );
- for (const sortedBook of sortedNames) {
- if (sortedBook.payed) {
- isPayed = "Has Paid";
- } else {
- isPayed = "Not Paid";
- }
- resultArr.push(
- `${sortedBook.bookName} == ${sortedBook.bookAuthor} - ${isPayed}.`
- );
- }
- return resultArr.join("\n");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement