valiamaximova1

Story classes

Feb 20th, 2021 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Story {
  2.     constructor(title, creator) {
  3.         this.title = title
  4.         this.creator = creator;
  5.         this.comments = [];
  6.         this.likes = [];
  7.         this.replies = [];
  8.     }
  9.  
  10.     get likes() {
  11.         if (this._likes.length <= 0) {
  12.             return `${this.title} has 0 likes`;
  13.         } else if (this._likes.length === 1) {
  14.             return `${this._likes} likes this story!`;
  15.         } else {
  16.             return `${this._likes[0]} and ${this._likes.length - 1} others like this story!`;
  17.         }
  18.     }
  19.  
  20.     set likes(value) {
  21.         this._likes = value;
  22.     }
  23.  
  24.     set comments(value) {
  25.         this._comments = value;
  26.     }
  27.  
  28.  
  29.     like(username) {
  30.         if (this.likes.includes(username)) {
  31.             throw new Error("You can't like the same story twice!");
  32.         }
  33.         if (this.creator === username) {
  34.             throw new Error("You can't like your own story!");
  35.         }
  36.         this._likes.push(username);
  37.         return`${username} liked ${this.title}!` ;
  38.     }
  39.  
  40.     dislike(username) {
  41.         if (!this.likes.includes(username)) {
  42.             throw new Error("You can't dislike this story!");
  43.         }
  44.         this._likes = this._likes.filter(e => e.username === username);
  45.         return `${username} disliked ${this.title}`;
  46.     }
  47.  
  48.     comment(username, content, id) {
  49.         if (this._comments.includes(id)) {
  50.             this.replies.push(id);
  51.             return "You replied successfully";
  52.         }else{
  53.             this._comments.push({id, username, content, Replies: 0});
  54.             return `${username} commented on ${this.title}`;
  55.         }
  56.  
  57.  
  58.  
  59.     }
  60.  
  61.     toString(sortingType) {
  62.         let res ='';
  63.  
  64.         if (sortingType === 'asc') {
  65.           this._comments.sort((a,b) => a.id.localeCompare(b.id));
  66.           this._comments.replies.sort((a,b) => a.id.localeCompare(b.id))
  67.         }
  68.         if (sortingType === 'desc') {
  69.             this._comments.sort((a,b) => b.id.localeCompare(a.id));
  70.             this._comments.replies.sort((a,b) => b.id.localeCompare(a.id))
  71.         }
  72.         res += `Title: ${this.title}\nCreator: ${this.creator}\nLikes: ${this._likes.length}\nComments:\n`
  73.             return res;
  74.         }
  75.  
  76. }
Add Comment
Please, Sign In to add comment