John_IV

Library

Jun 13th, 2020
1,456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Library {
  2.     libraryName;
  3.     subscribers;
  4.     subscriptionTypes = {
  5.         'normal': x => x.length,
  6.         'special': x => x.length * 2,
  7.         'vip': () => Number.MAX_SAFE_INTEGER
  8.     };
  9.  
  10.     constructor(libraryName) {
  11.         this.libraryName = libraryName;
  12.         this.subscribers = [];
  13.     }
  14.  
  15.     subscribe(name, type) {
  16.         if (this.subscriptionTypes[type] === undefined) {
  17.             throw new Error(`The type ${type} is invalid`);
  18.         }
  19.         let sub = this.subscribers.find(s => s.name === name);
  20.         if (sub === undefined) {
  21.             this.subscribers.push({name, type, books: []});
  22.         } else {
  23.             sub.type = type;
  24.         }
  25.         return sub;
  26.     }
  27.  
  28.     unsubscribe(name) {
  29.         let sub = this.subscribers.find(s => s.name === name);
  30.         if (sub === undefined) {
  31.             throw new Error(`There is no such subscriber as ${name}`);
  32.         } else {
  33.             this.subscribers.splice(this.subscribers.indexOf(sub), 1);
  34.         }
  35.         return this.subscribers;
  36.     }
  37.  
  38.     receiveBook(name, title, author) {
  39.         let sub = this.subscribers.find(s => s.name === name);
  40.         if (sub === undefined) {
  41.             throw new Error(`There is no such subscriber as ${name}`);
  42.         } else {
  43.             let max = this.subscriptionTypes[sub.type](name);
  44.             if (sub.books.length < max) {
  45.                 sub.books.push({title, author});
  46.             } else {
  47.                 throw new Error(`You have reached your subscription limit ${max}!`);
  48.             }
  49.         }
  50.         return sub;
  51.     }
  52.  
  53.     showInfo() {
  54.         if (this.subscribers.length > 0) {
  55.             let str = '';
  56.             this.subscribers.map(s => {
  57.                 let books = s.books.map(b => `${b.title} by ${b.author.trim()}`).join(', ');
  58.                 str += `Subscriber: ${s.name}, Type: ${s.type}\nReceived books: ${books.trim()}\n`;
  59.             })
  60.             return str;
  61.  
  62.         } else {
  63.             throw new Error(`${this.libraryName} has no information about any subscribers`);
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment