0

So I'm trying to make my code more modular for sanity purposes (and because it seems more efficient than writing the same code five+ different ways).

However, I'm running against a wall on this one as my JavaScript knowledge is apparently lacking. I've got a method call for buying various unit types. I want to check that the player has enough of a particular type of unit citizens or soldiers before training a more advanced type citizen.workers or soldier.specific. Incrementing the more advanced type isn't a problem I'm addressing yet; I'm simply trying to determine if the base unit is present in a minimum quantity.

What I'm currently using is not working. The type variable is not evaluating but is rather going through as "type" when I want it to default as "citizens". I'm using the variable in 2 places, the if statement for evaluation purposes and in the DB update to reduce the number of that particular field.

Current 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;
},

Searched all over but was not finding what I was looking for or even something I could start with and begin to apply it to what I needed. Any help would be great.

Edit: Yes I realized I was using a default value incorrectly for javascript. I've modified that in my code. The computed value David Weldon answered with was what I was going after more specifically.

0

1 Answer 1

1

Change your code in the following ways:

player[type] >= number

and

{$inc: {'credits': (0-cost), [type]: (0-number)}}

The latter is an example of a computed property key which is new in es6.

Also see the 'Variables as Keys' section of common mistakes.

Sign up to request clarification or add additional context in comments.

2 Comments

That first line really helped get the if working. However my DB update line still isn't working. It's just decrementing type (which isn't what I'm wanting). I have your line as it was here in your answer and I'm not actually seeing a difference in what I already had. Your help is appreciated though!!
Thanks so much. I've done a bunch of basic tutorials just hadn't come across these types of things. Appreciate it and now my code is a bit more modular and concise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.