Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Library {
- constructor(libraryName) {
- this.libraryName = libraryName;
- this.subscribers = [];
- this.subscriptionTypes = {
- normal: libraryName.length,
- special: libraryName.length * 2,
- vip: Number.MAX_SAFE_INTEGER
- }
- }
- subscribe(name, type) {
- if (this.subscriptionTypes.hasOwnProperty(type) === false) {
- throw new Error(`The type ${type} is invalid`);
- }
- let subscriber = {
- name,
- type,
- books: []
- }
- let person = this.subscribers.find(p => p.name === name);
- if (person === undefined) {
- this.subscribers.push(subscriber);
- } else {
- person.type = type;
- }
- return subscriber;
- }
- unsubscribe(name) {
- let person = this.subscribers.find(p => p.name === name);
- if (person) {
- let index = this.subscribers.indexOf(person);
- this.subscribers.splice(index, 1);
- } else {
- throw new Error(`There is no such subscriber as ${name}`);
- }
- return this.subscribers;
- }
- receiveBook(subscriberName, bookTitle, bookAuthor) {
- let person = this.subscribers.find(p => p.name === subscriberName);
- if (!person) {
- throw new Error(`There is no such subscriber as ${subscriberName}`);
- } else {
- let limit = this.subscriptionTypes[person.type];
- if (person.books.length < limit) {
- let book = { bookTitle, bookAuthor };
- person.books.push(book);
- } else {
- throw new Error(`You have reached your subscription limit ${limit}!`);
- }
- }
- return person;
- }
- showInfo() {
- let result = [];
- if (this.subscribers.length === 0) {
- return `${this.libraryName} has no information about any subscribers`;
- } else {
- for (let subscriber of this.subscribers) {
- result.push(`Subscriber: ${subscriber.name}, Type: ${subscriber.type}`);
- let bookPrint = '';
- subscriber.books.forEach(b => bookPrint += `${b.bookTitle} by ${b.bookAuthor}, `);
- result.push(`Recived Books: ${bookPrint.substring(0, bookPrint.length - 2)}`);
- }
- }
- return result.join('\n');
- }
- }
- let lib = new Library('Lib');
- lib.subscribe('Peter', 'normal');
- lib.subscribe('John', 'special');
- lib.receiveBook('John', 'A Song of Ice and Fire', 'George R. R. Martin');
- lib.receiveBook('Peter', 'Lord of the rings', 'J. R. R. Tolkien');
- lib.receiveBook('John', 'Harry Potter', 'J. K. Rowling');
- console.log(lib.showInfo());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement