Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Library {
- libraryName;
- subscribers;
- subscriptionTypes = {
- 'normal': x => x.length,
- 'special': x => x.length * 2,
- 'vip': () => Number.MAX_SAFE_INTEGER
- };
- constructor(libraryName) {
- this.libraryName = libraryName;
- this.subscribers = [];
- }
- 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) {
- this.subscribers.push({name, type, books: []});
- } 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}`);
- } else {
- 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}`);
- } else {
- let max = this.subscriptionTypes[sub.type](name);
- 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}`).join(', ');
- str += `Subscriber: ${s.name}, Type: ${s.type}\nReceived books: ${books}\n`;
- })
- return str.trim();
- } else {
- throw new Error(`${this.libraryName} has no information about any subscribers`);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment