2

I've an array that is being used to store the conversion factors for a conversion program I'm currently working on.

A short Example:

var Length =
{
"lengthsA" :
{
    "inch" : 0.0254,
    "yard" : 0.9144,
    "mile" : 1609.344,
    "foot" : 0.3048,
    "metres": 1
}}

This will become much bigger and there are many more of them.

It seems I have two options. I can either declare many arrays, one for each conversion type and in the function use and if else to dictate which one should be called upon for the conversion. The alternative is to use one huge array that stores everything. This would nullify the need for an if else and also remove the need to declare many arrays but at the cost of combining everything into what could become one big mess.

I'm in favour of the first option, mainly because I like modularity and it'd be easier for debugging / editing.

I'm also concerned about speed and access time. With one large array would there be an impact seeing as I'm using keys to determine what values are called. Key above would be "lengthsA"

Thanks.

null
  • 3,469
  • 7
  • 41
  • 90
  • What's the purpose of having a two-level structure for `Length`? Would there also be a `"lengthsB"` entry in the full structure? Also, don't worry about performance; the difference (if any) will be unnoticeable. – Ted Hopp Jul 10 '13 at 16:21
  • yes, there's a lengthsB as well. thanks for answering re performance. I think it that case one larger obj and removing a ton of if else / case statements is the way forward – null Jul 10 '13 at 16:23

3 Answers3

2

If I were doing this project, I'd definitely use a hierarchical structure. I might start with something like this:

var conversions = {
    length : {
        lengthsA : {
            inch : 0.0254,
            yard : 0.9144,
            mile : 1609.344,
            foot : 0.3048,
            metres: 1
        },
        lengthsB : {
            . . .
        }
    },
    mass : {
    },
    . . .
}

The structure is: conversions.<category>.<conversion_group>.<unit_name>. It's probably as easy to maintain as any other structure.

You might consider adding a property reference that would indicate the name of the unit that should be the reference (e.g., reference : "metres" in the case of lengthsA). I'd also be more consistent about unit names ("inch" is singular; "metres" is plural). Depending on your application, you might also want to have each conversion be a structure with a value and an uncertainty. (Some conversion factors are exact; others are not.)

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Thanks. that is essentially what I have. I do need to address the names. I somehow got into an habit of writing kilometres, centimetres etc for the drop down list instead of singular, that has now made it's way into this table. Currently cleaning up code now. Thanks for mentioning it. Reference would also be useful. Thanks again – null Jul 10 '13 at 17:04
1

Hard to say without knowing all the details of your program, but I wouldn't use hierarchical objects for storing units, but rather a flat array, similar to a SQL table:

units = [
    { category: "length", name: "inch" , value: 0.0254   },
    { category: "length", name: "yard" , value: 0.9144   },
    { category: "length", name: "mile" , value: 1609.344 },
    { category: "length", name: "foot" , value: 0.3048   },
    { category: "length", name: "meter", value: 1        }
]

You will need a couple of utility functions to find items in this table (like getUnitsByCategory), but once you've got it, you'll find this structure much easier to work with. Uniformity is the king!

georg
  • 211,518
  • 52
  • 313
  • 390
  • Why do you advise against using hierarchical objects? Is it personal preference? At the moment I'm looking for speed. Especially when entering all the values, if I can avoid typing the same thing twice then I'm a tiny bit happier. It is working quite well at the moment, worry is later it might fail or slow performance a lot (although Ted answered that) – null Jul 10 '13 at 16:30
  • in this case you need alot of if conditions... checking the category and the name... a hierarchial object can have direct access from buttons, select boxes and more.. just by the string it contains. – cocco Jul 10 '13 at 17:11
  • @SteveGreen: no, I didn't type the word "category" five times when writing my answer, in case you mean that. – georg Jul 10 '13 at 18:16
0

if you define variable for javascript so..

var inch=0.0254,
yard=0.9144

youcan write

<option>inch</option>

and acces it with

window[document.select.textContent]

it's much faster but the code would be much longer.

In your case the readability is more important

so yes create a multidiminsional object.(groups)

it's also easier to access the values.

obj={
 "length":{
  inches:0.0254,
  miles:1609.344,
 },
 "weight":{
  kg:1  
 }
}

so you can access it by

obj.length.inches

or

 obj['length']['inches']

and write

window.onload=function(){
var obj={
 length:{
  inches:0.0254,
  miles:1609.344,
 }
}
var select1=document.createElement('select'),
select2=null,
f=document.createDocumentFragment(),
input=document.createElement('input'),
convert=document.createElement('button');
for(var a in obj.length){
 f.appendChild(document.createElement('option')).textContent=a;// easyway to access
}
select1.appendChild(f);
select2=select1.cloneNode(true);
input.type='text';
convert.textContent='Convert';

convert.addEventListener('click',function(e){
 console.log(
  input.value,
  obj.length[select1.textContent],// easyway to access
  obj.length[select2.textContent]// easyway to access
)
},false);

var bdy=document.body
bdy.appendChild(input);
bdy.appendChild(select1);
bdy.appendChild(select2);
bdy.appendChild(convert);
}
cocco
  • 16,442
  • 7
  • 62
  • 77
  • 1
    _"it's much faster"_ -- on what basis are you claiming this? Compared to what? – Ted Hopp Jul 10 '13 at 16:23
  • if he bach converts alot of values direct acces to a variable if much faster then looping through objects or arrays. i hade a similar problem where i had to loop through 1000's of objects and crashed the ios... using static variables it's 1.100 times faster and it didn't crashed the system. – cocco Jul 10 '13 at 16:25
  • Looking up an object property by name could easily be much faster than running through a series of `if/else` tests to determine which variable to use. – Ted Hopp Jul 10 '13 at 16:31
  • depends.. he could create more functions acessing the variables... static way... but yeah i ddon't know how many categories and types he has. – cocco Jul 10 '13 at 16:33
  • @TedHopp in all modern engines making "object property by name" a fixed c struct access (1 machine instruction in best case) is a fundamental optimization, so it will indeed be much, much faster. Of course this is assuming that one doesn't trigger the heuristics to cause hash table deoptimization. – Esailija Jul 10 '13 at 16:55
  • i don't understand half of what @Esailija wrote.. but i think it's that what i want to explain with my poor english ... sry. – cocco Jul 10 '13 at 17:08
  • 1
    @Esailija - Thanks for the comment about engine optimization. My point is that even if accessing `var a` is faster than accessing `obj.a`, performance depends just as much on other factors, not the least of which is how much additional work the code has to do to deal with one data structure (a collection of individually named variables) versus another (an object with values indexed by property name). (cocco - if I read Esailija's comment correctly, I think its in support of my second comment.) – Ted Hopp Jul 10 '13 at 17:16
  • yeah and if you read my answer i suggested him to use objects.and also added some tips to access it with only one function and no if conditions.basically he has just to add alittle math. – cocco Jul 10 '13 at 17:19
  • you can also write window['inches'] and again no if/else. – cocco Jul 10 '13 at 17:29