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 = [];
- this._likes = [];
- this._counter = 1;
- }
- get likes() {
- if (this._likes.length === 0) {
- return `${this.title} has 0 likes`;
- } else if (this._likes.length === 1) {
- return `${this._likes[0]} likes this story!`;
- } else {
- 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!');
- } else if (username === this.creator) {
- throw new Error('You can\'t like your own story!');
- } else {
- this._likes.push(username);
- return `${username} liked ${this.title}!`;
- }
- }
- dislike(username) {
- if (!this._likes.includes(username)) {
- throw new Error('You can\'t dislike this story!')
- } else {
- let theIndex = this._likes.indexOf(username);
- this._likes.splice(theIndex, 1);
- return `${username} disliked ${this.title}`;
- }
- }
- comment(username, content, id) {
- let temp = this._comments.find(e => e.id === id);
- if (temp === undefined || id === undefined) {
- let newTemp = {
- id: this._counter,
- username: username,
- content: content,
- replies: []
- }
- this._comments.push(newTemp);
- this._counter++;
- return `${username} commented on ${this.title}`;
- } else {
- let replayNumber = temp.replies.length + 1;
- let replayObject = {
- id: `${id}.${replayNumber}`,
- username: username,
- content: content
- }
- temp.replies.push(replayObject);
- return `You replied successfully`;
- }
- }
- toString(sortingType) {
- let sb = [];
- let temp = `Title: ${this.title}`;
- sb.push(temp);
- temp = `Creator: ${this.creator}`;
- sb.push(temp);
- temp = `Likes: ${this._likes.length}`;
- sb.push(temp);
- sb.push('Comments:');
- // sortinng
- if (sortingType === 'asc') {
- this._comments.sort((a, b) => a.id - b.id);
- for (let i = 0; i < this._comments.length; i++){
- this._comments[i].replies.sort((a, b) => a.id - b.id);
- }
- } else if (sortingType === 'desc') {
- this._comments.sort((a, b) => (b.id) - (a.id));
- for (let i = 0; i < this._comments.length; i++){
- this._comments[i].replies.sort((a, b) => (b.id) - (a.id));
- }
- } else if (sortingType === 'username') {
- this._comments.sort((a, b) => a.username.localeCompare(b.username));
- for (let i = 0; i < this._comments.length; i++){
- this._comments[i].replies.sort((a, b) => a.username.localeCompare(b.username));
- }
- }
- // sb.appendLine()
- this._comments.forEach(e => {
- temp = `-- ${e.id}. ${e.username}: ${e.content}`;
- sb.push(temp);
- e.replies.forEach(i => {
- temp = `--- ${i.id}. ${i.username}: ${i.content}`;
- sb.push(temp);
- });
- });
- return sb.join('\n');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement