1

I want to store some extra data about an object (in this case, a recipe) without storing it in the object itself. What is the best way of doing this?

Here is a simple example. Am I doing something wrong architecturally?

var recipes = {
    scones: {egg:2, milk: 5},
    pancakes: {eggs:3, milk: 2}
}

var recipesCooked = {
    scones: 0,
    pancakes: 0
}

function makeRecipe(recipe){

  // I don't want to have to do this loop every time.
  // Is there a better way of storing this data??
  for(var key in recipes) {
    if(recipes.hasOwnProperty(key) && recipes[key] === recipe){
      recipesCooked[key]++;
    }
  }
  //...snipped...make the recipe
}

makeRecipe(recipes.pancakes);
//recipesCooked.pancakes should be 1

In other words: I need some way of tying the extra data (recipesCooked) to the correct recipe, and the only way I know of doing that is by using the same key. But this seems bad, especially because I have to iterate back through the recipes to find the name of the key.

Zee
  • 15
  • 3

2 Answers2

0

Do you need to pass the whole recipe in? Could you not just pass the key in?

function makeRecipe(key){
    var recipe = recipes[key];
    if (recipe != null && recipesCooked[key] != null)) {
       recipesCooked[key]++
       //...snipped...make the recipe
    }
}
Pete
  • 57,112
  • 28
  • 117
  • 166
  • but OP clearly states they don't want properties added to `recipes` object – charlietfl Mar 04 '15 at 12:39
  • @charlietfl Sorry, never saw that bit - was still half asleep. Changed my answer – Pete Mar 04 '15 at 13:10
  • I guess I could pass the key in. After learning strongly typed languages, it just seemed wrong to be passing around random strings to represent objects. I'm now trying to think of a good reason why I shouldn't do this. – Zee Mar 04 '15 at 13:32
  • Yeah, but I think it's the only way of using the key without having to loop through the objects, although you could created some sort of [js enum](http://stackoverflow.com/questions/287903/enums-in-javascript) so that you pass in a strongly typed key – Pete Mar 04 '15 at 14:38
0

Maybe you need to change the signature of makeRecipe. There shoulnd't need to be a loop:

var recipes = {
    scones: {egg:2, milk: 5},
    pancakes: {eggs:3, milk: 2}
}

// no need for properties, [makeRecipe] takes care of that
var recipesCooked = { };

// parameter recipe should be a string
function makeRecipe( recipe ){
  if (!recipes[recipe]) { throw 'recipe ' + reicpe + ' not found'; }
  if (recipe in reicpesCooked) { recipesCooked[recipe] += 1; }
  else { recipesCoocked[reciped] = 1; }
  // and start cooking
}

makeRecipe('scones');
KooiInc
  • 119,216
  • 31
  • 141
  • 177