Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Story {
- constructor(title, creator) {
- this.title = title;
- this.creator = creator;
- this._comments = []; // {Id, Username, Content, Replies: [{Id, Username, Content}]}
- this._likes = []; //usernames
- }
- get likes() {
- if (this._likes.length === 0) {
- return `${this.title} has 0 likes`;
- }
- if (this._likes.length === 1) {
- return `${this._likes[0]} likes this story!`;
- }
- return `${this._likes[0]} and ${
- this._likes.length - 1
- } others like this story!`;
- }
- like(username) {
- if (this._likes.includes(username)) {
- throw new Error("You can't like the same story twice!");
- }
- if (this.creator === username) {
- throw new Error("You can't like your own story!");
- }
- this._likes.push(username);
- return `${username} liked ${this.title}!`;
- }
- dislike(username) {
- let idx = this._likes.findIndex((u) => u === username);
- if (idx === -1) {
- throw new Error("You can't dislike this story!");
- }
- this._likes.splice(idx, 1);
- return `${username} disliked ${this.title}`;
- }
- comment(username, content, id) {
- let existingComment = this._comments.find((c) => c.Id === id);
- if (id === undefined || existingComment === undefined) {
- this._comments.push({
- Id: this._comments.length + 1,
- Username: username,
- Content: content,
- Replies: [],
- });
- return `${username} commented on ${this.title}`;
- }
- existingComment.Replies.push({
- Id: `${id}.${existingComment.Replies.length + 1}`,
- Username: username,
- Content: content,
- });
- return 'You replied successfully';
- }
- toString(sortingType) {
- let result = [
- `Title: ${this.title}
- Creator: ${this.creator}
- Likes: ${this._likes.length}
- Comments:`,
- ];
- let sorted;
- if (sortingType == 'asc') {
- this._comments
- .sort((a, b) => a.Id - b.Id)
- .forEach((c) => c.Replies.sort((a, b) => a.Id - b.Id));
- } else if (sortingType == 'desc') {
- this._comments
- .sort((a, b) => b.Id - a.Id)
- .forEach((c) => c.Replies.sort((a, b) => b.Id - a.Id));
- } else if (sortingType == 'username') {
- this._comments
- .sort((a, b) => a.Username.localeCompare(b.Username))
- .forEach((c) =>
- c.Replies.sort((a, b) =>
- a.Username.localeCompare(b.Username)
- )
- );
- }
- this._comments.forEach((c) => {
- result.push(`-- ${c.Id}. ${c.Username}: ${c.Content}`);
- c.Replies.forEach((r) =>
- result.push(`--- ${r.Id}. ${r.Username}: ${r.Content}`)
- );
- });
- return result.join('\n');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement