I need to store data to represent this:
Water + Fire = Steam
Water + Earth = Mud
Mud + Fire = Rock
The goal is the following: I have draggable HTML divs, and when <div id="Fire"> and <div id="Mud"> overlap, I add <div id="Rock"> to the screen. Ever played Alchemy on iPhone or Android? Same stuff
Right now, the way I’m doing this is a JS object :
var stuff = {
'Steam' : { needs: [ 'Water', 'Fire'] },
'Mud' : { needs: [ 'Water', 'Earth'] },
'Rock' : { needs: [ 'Mud', 'Fire'] },
// etc...
};
and every time a div overlaps with another one, I traverse the object keys and check the ‘needs’ array.
I can deal with that structure but I was wondering if I could do any better?
Edit: I should add that I also need to store a few other things, like a short description or an icon name. So typicall I have Steam: { needs: [ array ], desc: "short desc", icon:"steam.png"},
Final edit: thank you everyone for contributing, I found really valuable input in all your comments
If you don’t mind including another external library and are comfortable with LINQ, you can use linq.js for this.
Notes
Enumerable.From(stuff)splits yourstuffobject into itsKeyandValueparts.For instance,
Keywould refer to"Rock"andValueto{ needs: ['Mud', 'Fire'] }.ToLookup()creates a look-up dictionary from that. It takes 3 parameters:"$.Value.needs")Key)['Mud', Fire']becomes"Fire+Mud").Get()function finds a match for its argument, using the same transformation function.Note that a string argument like
"$.Value.needs"is a shorthand forfunction ($) { return $.Value.needs; }.linq.js also provides many more useful functions that can transform complex tasks into one-liners.
Edit: Returning all the additional info from the lookup would be as simple as:
The purpose of the Lookup object is to increase speed. You could also traverse the entire object graph every time:
Note that
.Select()is optional. You could remove it, in which case the result would be the same as in the previous example.