Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Article {
- _comments = [];
- _likes = [];
- constructor(title, creator) {
- this.title = title,
- this.creator = creator
- }
- 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._likes[0]} 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 (username === this.creator) {
- throw new Error("You can't like your own articles!")
- }
- this._likes.push(username)
- return `${username} liked ${this.title}!`
- }
- dislike(username) {
- if (this._likes[0] !== username) {
- throw new Error("You can't dislike this article!")
- }
- this._likes.shift()
- return `${username} disliked ${this.title}`
- }
- comment(username, content, id) {
- let comment = this._comments.find(o => o.id === id)
- if (id === undefined || comment === undefined) {
- id = this._comments.length + 1
- comment = { id: id, username: username, content: content, replies: [] };
- this._comments.push(comment)
- return `${username} commented on ${this.title}`
- }
- if (comment !== undefined) {
- let replyId = `${id}.${comment.replies.length + 1}`
- let reply = { id: replyId, username: username, content: content }
- comment.replies.push(reply);
- return "You replied successfully"
- }
- }
- toString(sortingType) {
- if (sortingType === "asc") {
- this._comments = this._comments.sort((a, b) => {
- return Number(a.id) - Number(b.id)
- })
- this._comments.forEach(comment => {
- comment.replies.sort((a, b) => {
- return Number(a.id) - Number(b.id)
- })
- })
- }
- if (sortingType === "desc") {
- this._comments = this._comments.sort((a, b) => {
- return Number(b.id) - Number(a.id)
- })
- this._comments.forEach(comment => {
- comment.replies.sort((a, b) => {
- return Number(b.id) - Number(a.id)
- })
- })
- }
- if (sortingType === "username") {
- this._comments.sort((a, b) => {
- return a.username.localeCompare(b.username)
- })
- this._comments.forEach(comment => {
- comment.replies.sort((a, b) => {
- return a.username.localeCompare(b.username)
- })
- })
- }
- let result = `Title: ${this.title}\n` + `Creator: ${this.creator}\n` + `Likes: ${this._likes.length}\n` + `Comments:\n`
- this._comments.forEach(comment => {
- result += `-- ${comment.id}. ${comment.username}: ${comment.content}\n`;
- comment.replies.forEach(reply => {
- result += `--- ${reply.id}. ${reply.username}: ${reply.content}\n`
- })
- })
- return result.trim()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement