Home > Software design >  Is there any way to combine these functions into one or two functions?
Is there any way to combine these functions into one or two functions?

Time:10-06

I am learning javaScript and am trying to make a scoreboard counter. So far, my code looks pretty messy and DRY. Is there any way to combine the home and guest score functions into one function for each?

 /*Scoring*/

let homeScore = 0
let guestScore = 0

const homeScoreCard = document.getElementById("home-score");
const guestScoreCard = document.getElementById("guest-score");


function increaseHomeScore(n) {
    homeScoreCard.innerHTML = homeScore  = n
 }

function increaseGuestScore(n) {
    guestScoreCard.innerHTML = guestScore  = n
 }

function threePoints() {
    increaseHomeScore(3);
}

function twoPoints() {
    increaseHomeScore(2);  
}

function onePoint() {
    increaseHomeScore(1);
}

function gThreePoints() {
    increaseGuestScore(3);
}

function gTwoPoints() {
    increaseGuestScore(2);
}

function gOnePoint() {
    increaseGuestScore(1);
}

CodePudding user response:

The function can take a parameter of how much to increase the score by:

function increaseHomeScore(n) {
   homeScoreCard.innerHTML = homeScore  = n
}

Then when you want to increase the home team score, you can call the function like this:

increaseHomeScore(2);

CodePudding user response:

Yes. Here's a possible solution.

function handleScoreChange(score, elem) {
elem.innerText = score
}

Here is the function. This way you may pass the score you want to add as first argument to the function. The second argument is reference to the "team node" in your webpage.

  • Related