views:

73

answers:

2

I'm trying to calculate somebody's bowel health based on a points system. I can edit the data structure, or logic in any way. I'm just trying to write a function and data structure to handle this ability.

Pseudo calculator function:

// Bowel health calculator
var points = 0;

If age is from 30 and 34:
    points += 1
If age is from 35 and 40:
    points += 2

If daily BMs is from 1 and 3:
    points -= 1
If daily BMs is from 4 and 6:
    points -= 2

return points;

Pseudo data structure:

var points_map = {
    age:
    {
        '35-40': 1,
        '40-45': 2,
        '45-50': 6,
        '50-55': 2,
        '55-60': 1,
        '60-65': 4,
        '65-70': 3,
        '70-75': 1,
        '75-150': 2
    },

    dbm:
    {
        '1-3': -1,
        '4-6': -2,
        '7-9': -3,
        '10-150': 5
    }

    // This plus about 10 more metrics like them (all with the same "Map a plus or minus value to each range" logic)
};

I have a full spreadsheet of data like this, and I am trying to write a DRY version of code and a DRY version of this data (ie, probably not a string for the '30-34', etc) in order to handle this sort of thing without a humongous number of switch statements.

+2  A: 

I'd think a better structure might have something like:

{
[35,1],
[40,2],
[45,6],
...
[150, null]
},

then do a loop on it:

for (var i =0; i<points_map.age.length-1; i++)
 {
 if (val >= points_map.age[i][0] && val<points_map.age[i+1][0])
    points += points_map.age[i][1];
 }

This could be made a little more efficient if needed but you get the idea.

rob
@rob, +1 - thanks. This helps. I'll use 2-length lists for each of them like that.
orokusaki
A: 

Depending on what the rest of the data looks like, you might be well served to assign point values to an object directly instead of ranges, i.e.:

var ruleMap = {
  age: { 35:1, 36:1, 37:1, 38:1, 39:1, 40:1,
         41:2, 42:2, 43:2, 44:2, 45:2 
       },
  dbm: { 1: -1, 2: -1, 3: -1, 
         4: -2, 5: -2, 6: -2 
       }
};

etc.

That probably looks a bit clunky, but it's easy to do in vim or emacs, and the logic for the loop is more readable if you have a patient array with all the necessary information like so:

var patient = { 
  age: 36, 
  dbm: 2 
};

Then your loop looks like:

var healthScore = 0;
for (var rule in ruleMap) {
  healthScore += ruleMap[rule][patient[rule]];
}
Will