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 = 0;
- this.users = [];
- this.commentsId = 0;
- this.repliesId = 0;
- }
- get likes() {
- if (this._likes === 0) {
- return `${this.title} has 0 likes`;
- } else if (this._likes === 1) {
- return `${this.users[0]} likes this article!`;
- } else {
- return `${this.users[0]} and ${this._likes} others like this article!`;
- }
- }
- like(username) {
- if (this.users.includes(username)) {
- throw new Error(`You can't like the same article twice!`);
- } else if (this.creator === username) {
- throw new Error(`You can't like your own articles!`);
- } else {
- this.users.push(username);
- this._likes += 1;
- return `${username} liked ${this.title}!`;
- }
- }
- dislike(username) {
- if (!this.users.includes(username)) {
- throw new Error(`You can't dislike this article!`);
- } else {
- this._likes -= 1;
- let index = this.users.indexOf(username);
- this.users.splice(index, 1);
- return `${username} disliked ${this.title}`;
- }
- }
- comment(username, content, id) {
- if (!this._comments.hasOwnProperty(id) || id === undefined) {
- this._comments[++this.commentsId] = {
- username: username,
- content: content,
- replies: [],
- };
- return `${username} commented on ${this.title}`;
- } else {
- this._comments[id].replies.push({
- id: `${id}.${++this.repliesId}`,
- username: username,
- content: content,
- });
- return `You replied successfully`;
- }
- }
- toString(sortingType) {
- let result = [
- `Title: ${this.title}`,
- `Creator: ${this.creator}`,
- `Likes: ${this._likes}`,
- `Comments:`,
- ];
- let sortedComments = null;
- if (sortingType === "asc") {
- sortedComments = Object.entries(this._comments).sort(
- (a, b) => a[0] - b[0]
- );
- } else if (sortingType === "desc") {
- sortedComments = Object.entries(this._comments).sort(
- (a, b) => b[0] - a[0]
- );
- } else {
- sortedComments = Object.entries(this._comments).sort((a, b) =>
- a[1].username.localeCompare(b[1].username)
- );
- }
- for (const [key, value] of sortedComments) {
- result.push(`-- ${key}. ${value.username}: ${value.content}`);
- if (value.replies.length > 0) {
- if (sortingType === "asc") {
- let sorted = value.replies.sort((a, b) => a.id - b.id);
- for (const s of sorted) {
- result.push(`--- ${s.id}. ${s.username}: ${s.content}`);
- }
- } else if (sortingType === "desc") {
- let sorted = value.replies.sort((a, b) => b.id - a.id);
- for (const s of sorted) {
- result.push(`--- ${s.id}. ${s.username}: ${s.content}`);
- }
- } else {
- let sorted = value.replies.sort((a, b) =>
- a.username.localeCompare(b.username)
- );
- for (const s of sorted) {
- result.push(`--- ${s.id}. ${s.username}: ${s.content}`);
- }
- }
- }
- }
- return result.join("\n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment