Advertisement
Lulunga

exam prep 03. Library Class

Oct 26th, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Library {
  2.  
  3.     constructor(libraryName) {
  4.         this.libraryName = libraryName;
  5.         this.subscribers = [];
  6.         this.subscriptionTypes = {
  7.             normal: this.libraryName.length,
  8.             special: this.libraryName.length * 2,
  9.             vip: Number.MAX_SAFE_INTEGER
  10.         };
  11.     }
  12.  
  13.     subscribe(name, type) {
  14.  
  15.         // Object.keys(this.subscriptionTypes).includes(type)
  16.         if (!this.subscriptionTypes[type]) {
  17.             throw new Error(`The type ${type} is invalid`)
  18.         }
  19.  
  20.         const found = this.subscribers.find(s => s.name === name);
  21.  
  22.         if (!found) {
  23.             this.subscribers.push({
  24.                 name,
  25.                 type,
  26.                 books: []
  27.             });
  28.         } else {
  29.             found.type = type;
  30.         }
  31.         return found ? found : this.subscribers[this.subscribers.length - 1];
  32.     }
  33.  
  34.     unsubscribe(name) {
  35.         const found = this.subscribers.findIndex(s => s.name === name);
  36.  
  37.         if (found === -1) {
  38.             throw new Error(`There is no such subscriber ${name}`);
  39.         }
  40.  
  41.         this.subscribers.splice(found, 1);
  42.         return this.subscribers;
  43.     }
  44.  
  45.     receiveBook(subscriberName, bookTitle, bookAuthor) {
  46.         const foundSubscriber = this.subscribers.find(s => s.name === subscriberName);
  47.  
  48.         if (!foundSubscriber) {
  49.             throw new Error(`There is no such subscriber as ${subscriberName}`);
  50.         }
  51.  
  52.         const subType = foundSubscriber.type;
  53.         const booksCount = this.subscriptionTypes[subType];
  54.  
  55.         if (foundSubscriber.books.length >= booksCount) {
  56.             throw new Error(`You have reached your subscription limit ${booksCount}!`);
  57.         }
  58.  
  59.         foundSubscriber.books.push({title: bookTitle, author: bookAuthor});
  60.  
  61.         return foundSubscriber;
  62.     }
  63.  
  64.     showInfo() {
  65.         if (this.subscribers.length === 0) {
  66.             return `${this.libraryName} has no information about any subscribers`;
  67.         }
  68.  
  69.         return this.subscribers.map(s => {
  70.             const booksOutput = s.books
  71.                 .map(b => `${b.title} by ${b.author}`)
  72.                 .join(', ');
  73.  
  74.             return `Subscriber: ${s.name}, Type: ${s.type}\nReceived books: ${booksOutput}`;
  75.  
  76.         }).join('\n');
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement