Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have a render function:

render: function(playerId) {
    this.getTotalPoints(playerId);
    // and some other code after this;
}

This render function may be executed with or without a playerId.

This is the getTotalPoints function:

getTotalPoints: function(playerId) {
     if (playerId) {
         this.allplayers[playerId].totalPoints = this.calculatePoints(this.allplayers[playerId].cards);
     } else {
         this.allplayers.forEach(function(element, index) {
             element.totalPoints = this.calculatePoints(element.cards);
         }.bind(this));
     }
 }

And the third function that actually calculates the points:

calculatePoints: function(cards) {
    points = 0;

    for (var i = 0; i < cards.length; i++) {
        points += cards[i].points;
    };

    return points;
}

I am repeating myself in getTotalPoints, where I have a call to this.calculatePoints - one for a single player and then one for all the players, depending on whether the playerId is set or not.

Is there any chance I can avoid this and simplify the code?

share|improve this question
    
Please state only the code's purpose in the title. –  Jamal 18 hours ago

1 Answer 1

Split code of getTotalPoints function into two steps:

  1. Save list of players into temp variable. If playerId is specified, then create array with only one element;
  2. Call calculatePoints in a foreach.

Other suggestions:

  1. Put var before points variable in calculatePoints function to move it from global to local scope;
  2. Rename getTotalPoints function to updateTotalPoints;
  3. Depending on the rest of your code it may be possible to pass array of players into render function. And move playerId check out of it.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.