Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Article {
- constructor(title, creator) {
- this.title = title;
- this.creator = creator;
- this._comments = [];
- this._likes = [];
- this.id = 1;
- this.first = '';
- }
- get likes() {
- if (this._likes.length === 0) {
- return `${this.title} has 0 likes`;
- }
- if (this._likes.length === 1) {
- return `${this._likes[0]} likes this article!`;
- }
- return `${this.first} and ${this._likes.length - 1} others like this article!`;
- }
- like(username) {
- if (this._likes.includes(username)) {
- throw new Error('You can\'t like the same article twice!');
- }
- if (this.creator === username) {
- throw new Error('You can\'t like your own articles!');
- }
- if (this._likes.length === 0) {
- this.first = username;
- }
- this._likes.push(username);
- return `${username} liked ${this.title}!`;
- }
- dislike(username) {
- if (!this._likes.includes(username)) {
- throw new Error('You can\'t dislike this article!');
- }
- let index = this._likes.findIndex(x => x === username);
- this._likes.splice(index, 1);
- return `${username} disliked ${this.title}`;
- }
- comment(username, content, id) {
- let commentExists = this._comments.find(x => x.id === id);
- if (!commentExists) {
- let obj = {
- id: this.id++,
- username: username,
- content: content,
- replies: []
- }
- this._comments.push(obj);
- return `${username} commented on ${this.title}`;
- }
- let replyObj = {
- id: `${id}.${commentExists.replies.length + 1}`,
- username: username,
- content: content
- }
- commentExists.replies.push(replyObj);
- return 'You replied successfully';
- }
- toString(sortingType) {
- if (sortingType === 'asc') {
- this._comments = this._comments.sort((a, b) => Number(a.id) - Number(b.id));
- }
- if (sortingType === 'desc') {
- this._comments = this._comments.sort((a, b) => Number(b.id) - Number(a.id));
- }
- if (sortingType === 'username') {
- this._comments = this._comments.sort((a, b) => a.username.localeCompare(b.username));
- }
- let result = '';
- result += `Title: ${this.title}\n`;
- result += `Creator: ${this.creator}\n`;
- result += `Likes: ${this._likes.length}\n`;
- result += `Comments:\n`;
- this._comments.forEach(x => {
- result += `-- ${x.id}. ${x.username}: ${x.content}\n`;
- let repliesComment = x.replies;
- if (sortingType === 'asc') {
- repliesComment = repliesComment.sort((a, b) => Number(a.id) - Number(b.id));
- }
- if (sortingType === 'desc') {
- repliesComment = repliesComment.sort((a, b) => Number(b.id) - Number(a.id));
- }
- if (sortingType === 'username') {
- repliesComment = repliesComment.sort((a, b) => a.username.localeCompare(b.username));
- }
- repliesComment.forEach(m => {
- result += `--- ${m.id}. ${m.username}: ${m.content}\n`;
- })
- })
- return result.trim();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement