Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Library {
- libraryName;
- subscribers;
- subscriptionTypes;
- constructor(libraryName) {
- this.libraryName = libraryName;
- this.subscribers = [];
- this.subscriptionTypes = {
- 'normal': this.libraryName.length,
- 'special': this.libraryName.length * 2,
- 'vip': Number.MAX_SAFE_INTEGER
- };
- // this.subscriptionTypes = {
- // normal: this.libraryName.length,
- // special: this.libraryName.length * 2,
- // vip: Number.MAX_SAFE_INTEGER
- // };
- }
- subscribe(name, type) {
- if (this.subscriptionTypes[type] === undefined) {
- throw new Error(`The type ${type} is invalid`);
- }
- let sub = this.subscribers.find(s => s.name === name);
- if (sub === undefined) {
- let newSub = {name, type, books: []};
- this.subscribers.push(newSub);
- return newSub;
- } else {
- sub.type = type;
- return sub;
- }
- }
- unsubscribe(name) {
- let sub = this.subscribers.find(s => s.name === name);
- if (sub === undefined) {
- throw new Error(`There is no such subscriber as ${name}`);
- }
- this.subscribers.splice(this.subscribers.indexOf(sub), 1);
- return this.subscribers;
- }
- receiveBook(name, title, author) {
- let sub = this.subscribers.find(s => s.name === name);
- if (sub === undefined) {
- throw new Error(`There is no such subscriber as ${name}`);
- }
- let max = this.subscriptionTypes[sub.type];
- if (sub.books.length < max) {
- sub.books.push({title, author});
- } else {
- throw new Error(`You have reached your subscription limit ${max}!`);
- }
- return sub;
- }
- showInfo() {
- if (this.subscribers.length > 0) {
- let str = '';
- this.subscribers.map(s => {
- let books = s.books.map(b => `${b.title} by ${b.author.trim()}`).join(', ');
- str += `Subscriber: ${s.name}, Type: ${s.type}\nReceived books: ${books.trim()}\n`;
- });
- return str;
- } else {
- return `${this.libraryName} has no information about any subscribers`;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment