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 = [];
- }
- set likes(x) {
- this._likes = x;
- }
- set comments(x) {
- this._comments = x;
- }
- get likes() {
- let hasLikesArr = this._likes.filter(x => x.likes === 1);
- if (hasLikesArr.length === 0) {
- return `${this.title} has 0 likes`;
- } else if (hasLikesArr.length === 1) {
- let result = "";
- this._likes.forEach(
- user => (result += `${user.username} likes this article!\n`)
- );
- return result.trim();
- } else {
- let firstLike = hasLikesArr[0].username;
- let totalLikes = hasLikesArr.length - 1;
- return `${firstLike} and ${totalLikes} others like this article!`;
- }
- }
- like(username) {
- const user = this._likes.find(u => u.username === username);
- if (user) {
- 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!");
- }
- this._likes.push({ username: username, likes: 1 });
- return `${username} liked ${this.title}!`;
- }
- dislike(username) {
- const user = this._likes.find(u => u.username === username);
- if (!user) {
- throw new Error("You can't dislike this article!");
- }
- user.likes--;
- return `${username} disliked ${this.title}`;
- }
- comment(username, content, id) {
- const comment = this._comments.find(c => c.id === id);
- if (comment === undefined) {
- this._comments.push({
- id: this._comments.length + 1,
- username: username,
- content: content,
- replies: []
- });
- return `${username} commented on ${this.title}`;
- }
- comment.replies.push({
- id: id + (comment.replies.length * 0.1 + 0.1),
- username: username,
- content: content
- });
- return "You replied successfully";
- }
- toString(sortingType) {
- let result = `Title: ${this.title}\nCreator: ${this.creator}\nLikes: ${
- this._likes.filter(x => x.likes === 1).length
- }\nComments:\n`;
- this._comments.sort(sortByCriteria).forEach(comment => {
- addToResult(comment, "comment");
- comment.replies
- .sort(sortByCriteria)
- .forEach(reply => addToResult(reply, "reply"));
- });
- function sortByCriteria(a, b) {
- const map = {
- asc: () => a.id - b.id,
- desc: () => b.id - a.id,
- username: () => a.username.localeCompare(b.username)
- };
- return map[sortingType]();
- }
- function addToResult(typeObj, type) {
- const map = {
- comment: () =>
- (result += `-- ${typeObj.id}. ${typeObj.username}: ${typeObj.content}\n`),
- reply: () =>
- (result += `--- ${typeObj.id}. ${typeObj.username}: ${typeObj.content}\n`)
- };
- return map[type]();
- }
- return result.trim();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment