HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Rendering function for total player points

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
totalplayerpointsfunctionforrendering

Problem

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?

Solution

Split code of getTotalPoints function into two steps:

  • Save list of players into temp variable. If playerId is specified, then create array with only one element;



  • Call calculatePoints in a foreach.



Other suggestions:

  • Put var before points variable in calculatePoints function to move it from global to local scope;



  • Rename getTotalPoints function to updateTotalPoints;



  • 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.

Context

StackExchange Code Review Q#87419, answer score: 3

Revisions (0)

No revisions yet.