John_IV

Library

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