I’m working in JavaScript and want to keep a list of set km/mph approximations to hand. (I can’t convert programmatically, I’m working with an external API that expects certain values, so it really does have to be a dictionary equivalent.)
Currently I’m using an object:
var KM_MPH = { 10: 16, 12: 20, 15: 24 };
Going from mph to km is pretty easy:
var km = KM_MPH[10];
How do I find mph, given km? Also, is an object the best data structure to use for this sort of thing in JavaScript? I’m more used to Python.
A basic JavaScript object is in fact the best choice here. To find a reverse mapping, you can do:
Or, if you anticipate having to do a lot of lookups, I would recommend having a secondary JS Object that is the mirror of the first
I don’t know if you are in fact doing this for conversion between kilometres per hour to miles per hour… if so, it seems to make more sense to just do the conversion directly instead of relying on a hash mapping of the values.