Currently, I am striving to enhance the modularity of my code for the sake of organization and efficiency. However, I have hit a roadblock due to a lack of knowledge in JavaScript.
I have a method call that pertains to purchasing different types of units. Before training a more advanced type like citizen.workers
or soldier.specific
, I need to verify if the player possesses enough of a particular type of unit, either citizens
or soldiers
. Right now, I am only focusing on determining if the base unit is available in the required quantity.
The current approach that I am using seems to be ineffective. The 'type' variable does not seem to evaluate properly; instead, it defaults to "type" when it should default as "citizens". This variable is used in two instances - within the if statement for evaluation and in the database update to decrement the specific field.
Here is the existing code:
'buy': function(cost, number, type) {
type = type || "citizens";
var currentUser = Meteor.user();
var player = Players.findOne({createdBy: currentUser._id});
if(player.credits >= cost && cost > 0 && player.type >= number && number > 0) {
Players.update({createdBy: currentUser._id}, {$inc: {'credits': (0-cost), type: (0-number)}});
return true;
}
return false;
},
I have searched extensively but have been unable to find a solution or even a starting point to address my needs. Any assistance would be greatly appreciated.
Edit: I acknowledge the mistake in utilizing a default value in JavaScript incorrectly. I have rectified this in my code. The computed value provided by David Weldon in his response aligns closely with what I am aiming to achieve.