Ivan Ivan - 3 months ago 14
Javascript Question

Creating methods inside forEach();

I am trying to create methods for the variable res. The expected result would be

res.add.wood('100')
. This would add 100 to the wood count.
res.get.wheat()
would get the amount of wheat.

Resources are ['wood', 'wheat', 'gold', 'meat'] and actions are ['get', 'set', 'add', 'sub']. I am not looking to define all of them as follows:

var resources = ['wood', 'wheat', 'gold', 'meat'];
var actions = ['get', 'set', 'add', 'sub'];

var res;

function res.get.wood() {
//
}

function res.set.wood() {
//
}

// 6 more to define.....


I am looking to find a way to make it faster.

The following code enables me to use
res.get()
,
res.set()
,
res.add()
and
res.sub()
:

var res = ['get', 'set', 'add', 'sub'];

res.forEach(function(arrayElement) {

res[arrayElement] = function() {
alert(arrayElement)
}

});


I need another loop, I have tried the following but it doesn't work:

res.forEach(function(arrayElement) {

['get', 'set', 'add', 'sub'].forEach(function(arrayInnerElement) {

res[arrayElement][arrayInnerElement] = function() {
alert(arrayInnerElement);
}

});
});


Thanks in advance!

Answer

I suggest something like this:

var resources = { 'wood': 50, 'wheat': 100, 'gold': 0, 'meat': 50 };

var resourceManager = (function(resources) {

  function Resource(amount) {
    this.amount = amount || 0;
  }
  Resource.prototype.get = function() {
    return this.amount;
  };
  Resource.prototype.set = function(amount) {
    this.amount = amount;
  };
  Resource.prototype.add = function(amount) {
    this.amount += amount;
  };
  Resource.prototype.sub = function(amount) {
    this.amount -= amount;
  };

  var o = {};
  Object.keys(resources).forEach(function(resource) {
    o[resource] = new Resource(resources[resource]);
  });
  return o;

}(resources));


var res = resourceManager;
console.log(res.wood.get()); // 50
res.wood.set(10);
console.log(res.wood.get()); // 10
res.wood.add(5);
res.wood.sub(2);
console.log(res.wood.get()); // 13