patternjavascriptMinor
Rendering function for total player points
Viewed 0 times
totalplayerpointsfunctionforrendering
Problem
I have a
This
This is the
And the third function that actually calculates the points:
I am repeating myself in
Is there any chance I can avoid this and simplify the code?
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:
Other suggestions:
- 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.