Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apologies in advance.

/* Add to the existing skeleton of a Tweet class in the space provided below.

  • A tweet should consist of an (dynamic) author, content, timeStamp, numberOfLikes, and comments.
  • A tweet should be capable of incrementing the numberOfLikes and adding to the list of comments.

Create multiple instances of your Tweet and log them to the console. Ensure that the tweet object instances perform as expected. */

class Tweet {
    constructor(author, content, timeStamp, numberOfLikes, comments) {
      this.author = author;
      this.content = content;
      this.timeStamp = timeStamp;
      this.numberOfLikes = numberOfLikes;
      this.comments = comments;
 }
};


//This is code I experimented with, but it's not functioning

this.add = function(numberOfLikes){
  for(i = 0; i < numberOfLikes.length; i++){
    console.log("You have " + numberOfLikes + " likes");
  }
}

this.add = function(comments) {
  for(i = 0; i < comments.length; i++) {
    console.log("You have " + comments + " comments");
  }
}



var tweet1 = new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, 6782);

Appreciate your help!

Answer №1

A tweet must have the ability to increase its number of likes.

To achieve this, a function should be implemented to increment the numberOfLikes.

Additionally, new comments can be added to the existing list.

The comments attribute is likely stored as an array. Therefore, it is essential to create a function that enables the addition of comments to the list.

class Tweet {
    constructor(author, content, timeStamp, numberOfLikes, comments) {
        this.author = author;
        this.content = content;
        this.timeStamp = timeStamp;
        this.numberOfLikes = numberOfLikes;
        this.comments = comments;
    }
    increaseNumberOfLikes() {
        this.numberOfLikes++
    }
    addComment(commentText) {
        this.comments.push(commentText)
    }
};

let tweet1 = new Tweet("The Weekend", "Some content", "15:31 P.M.", 9800, ["so cool", "do it again"])
tweet1.increaseNumberOfLikes()
tweet1.addComment("Great Song!")

console.log(tweet1)

You are encouraged to create additional tweets using the provided structure.

Answer №2

You have the ability to develop functions that utilize += and array#push for increasing numbers and appending values to arrays.

Increasing likes:

incrementLikes(increment = 1) {
  this.numberOfLikes += increment
}

Adding a new comment to the array:

addComment(comment) {
  this.comments.push(comment)
}

An important aspect I observed in your message was the mention of this.comments being listed. Therefore, I incorporated that modification during the class initialization.

new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, ["amazing", "wow"]);

Preview:

class Tweet {
  constructor(author, content, timeStamp, numberOfLikes, comments) {
    this.author = author;
    this.content = content;
    this.timeStamp = timeStamp;
    this.numberOfLikes = numberOfLikes;
    this.comments = comments;
  }
  
  incrementLikes(increment = 1) {
    this.numberOfLikes += increment
  }
  
  addComment(comment) {
    this.comments.push(comment)
  }
};

var tweet1 = new Tweet("Rihanna", "Fenty Beauty", "12:31 A.M.", 120193, ["amazing", "wow"]);

tweet1.incrementLikes()
console.log(tweet1.numberOfLikes)

tweet1.incrementLikes()
console.log(tweet1.numberOfLikes)

tweet1.addComment("This is a comment")
console.log(tweet1.comments)

Answer №3

To implement prototypal functions within a class, follow this structure:

class Post {
  constructor(author, content, timeStamp, numberOfLikes, comments) {
    this.author = author;
    this.content = content;
    this.timeStamp = timeStamp;
    this.numberOfLikes = numberOfLikes;
    this.comments = comments;
  }
  like() {
    this.numberOfLikes++;
  }
  comment(comment) {
    this.comments.push(comment);
  }
}

const post1 = new Post("Taylor Swift", "Folklore Album", "10:45 P.M.", 98765, ["Can't stop listening to this masterpiece"]);

console.log(post1.numberOfLikes);
post1.like();
post1.like();
console.log(post1.numberOfLikes);
console.log(post1.comments);
post1.comment("Best album of all time!")
console.log(post1.comments);
.as-console-wrapper { min-height: 100%!important; top: 0; }

Answer №4

This method should do the trick. Make sure to enclose the function definitions within the class definition. I've also adjusted the function names to avoid conflicts.

class SocialPost {
    constructor(author, postContent, timestamp, likesCount, comments) {
      this.author = author;
      this.postContent = postContent;
      this.timestamp = timestamp;
      this.likesCount = likesCount;
      this.comments = comments;
 }

  addLikes(likes){
    this.likesCount += likes
  }

    addComments(newComment) {
      this.comments += newComment
  }
};


// Creating an initial social post instance
var firstPost = new SocialPost("Jennifer", "New product launch", "2:45 P.M.", 23042, 953);

// Applying modifiers
firstPost.addLikes(10)
firstPost.addComments(5)

// Checking if the variables have been updated
console.log(firstPost.likesCount)
console.log(firstPost.comments)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vim: Turn off autocomplete when using insert mode key bindings

I've set up a mapping in insert mode to automatically indent brackets: inoremap [;<CR> [<CR>];<Esc>O<Tab> When I use it, the result looks like this (the pipe character represents the cursor): const a = [ | ]; Now, I want ...

creating a custom mongoose model using aggregation and filtering

My Review model includes two fields, product and rating. I want to calculate the total rating for a specific product and then find the average by dividing that total by 5. const mongoose = require('mongoose'); const ReviewSchema = mongoose.Sche ...

Difficulty in extracting data from child elements of JSON documents

Below is the JSON String: "book_types": { "type": "1", "books": [ { "name": "default", "cover": null, "lastUpdated": { "microsecond": 114250, "ctime": "Fri Aug 9 01:27:45 ...

When the width is reduced to a certain point, the display will change to inline-block, preserving the layout structure

My goal is to maintain a two-column layout for my container boxes, even when the browser width is minimized to 600px in my fiddle. The issue arises with the CSS rule display: inline-block causing the boxes to stack into a single column. Important point: I ...

Ensuring session data is updated when saving a mongoose model

I am facing a challenge with updating express session data in the mongoose save callback. Is there a way to access and modify the session data from within line 4 of the code? app.get('/', function(req, res){ var newModel = new Model(somedata); ...

Struggle with incorporating a file

As part of the login process, I have two options available: easy login and standard login. The easy login requires an employee ID, birthdate, and captcha answer, while the standard login asks for first name, last name, birthdate, and captcha. To facilitate ...

Unable to retrieve hours from MongoDB date array

Whenever I fetch data from my NodeJS+MongoDB webservice, I am able to retrieve the date format successfully. However, I am facing an issue when trying to extract hours from it. Here is how the date looks in MongoDB: https://i.stack.imgur.com/qxWGL.png I ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

What is the best way to apply a hover rule to a CSS class in order to change the color of a specific row when hovering in

I have managed to successfully apply a classname and add color to a specific row in my react-table. However, I am facing difficulty in adding a hover rule to this className to change the color when I hover over the row. Can someone guide me on how to apply ...

An alternative method for storing data in HTML that is more effective than using hidden fields

I'm trying to figure out if there's a more efficient method for storing data within HTML content. Currently, I have some values stored in my HTML file using hidden fields that are generated by code behind. HTML: <input type="hidden" id="hid1 ...

What causes the discrepancy in the expiresIn value of my JWT when it is transmitted from the server to the front-end?

After setting the token expiry date on the server, I decided to log out the value to double-check it. However, upon checking the value on my React front-end, I noticed a significant change in the value received compared to what was sent from the server. Is ...

Changing the colors of multiple buttons in a React Redux form: a step-by-step guide

When using Redux Form Wizard on the second page, I have two buttons that ask for the user's gender - Male or Female. The goal is to make it so that when a user clicks on either button, only that specific button will turn orange from black text. You ...

Updating a JSON data structure after removing an item using AngularJS

As a newcomer to AngularJS, I have created a Service using Java and integrated it into Angular to handle the deletion of Contact objects. On my homepage in AngularJS, this is the code I have: <!--RESULTS--> <form> <table class="table table ...

How can we enable SOAJS to operate on NodeJS versions higher than 0.12?

Currently, We were required to revert our NodeJS platform back to version 0.12 in order for our SOAjs dashboard to function properly. What changes need to be made in our SOAjs implementation to support the latest NodeJS versions? Thank you ...

Utilizing Angular 9 with Jest for unit testing: simulating a promise, checking for method invocation afterwards

I'm in need of assistance as I am unsure how to mock a promise and verify that a method is called within the then() block. When I click on the save button of my form, my code appears as follows: // File: myComponent.ts save() { const myObject = n ...

What steps should I take to design and implement this basic search form?

Essentially, I have a three-page setup: - One page containing all possible search results such as: 'search result 1' 'search result 2' 'search result 3' - Another page with a search form and enter button. - And finally, a res ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

"Utilizing Jquery for interactive menu functionality - delivering the requested JSON

I have successfully implemented a dynamic menu using jQuery that parses a JSON response file to create the menu. However, instead of having the menu items link to URLs, I want them to retrieve and parse JSON data from those URLs. Despite my efforts, the me ...

Unable to integrate multiple webpack projects: Uncaught SyntaxError occurs due to a missing closing parenthesis after the argument list

My website features a section where clients can track their projects. One aspect of the site involves viewing a blueprint created using THREE.js and bundled with webpack. I have been tasked with adding another type of blueprint to the site. I have success ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...