# Calculating premium from a rate chart

I have to calculate the premium from a rate chart based on a person's age and the amount of insurance they request. I started out using if/switch statements, but the code is getting too long and seems pretty redundant.

var premium;
var beneAmt = $('#PrimaryApplicantTTLBenefitAmountInput').val(); var age =$('#PrimaryApplicantAge').val();

if (50000 <= beneAmt < 75000) {

switch (true) {

case (age < 30):

break;

case (30 <= age < 40):

break;

case (40 <= age < 50):

break;

case (50 <= age < 60):

break;

case (60 <= age < 65):

break;

case (65 <= age < 70):

break;

case (70 <= age < 75):

break;

case (age >= 75):

break;

}

} else if (75000 <= beneAmt < 100000) {

switch (true) {

case (age < 30):

break;

case (30 <= age < 40):

break;

case (40 <= age < 50):

break;

case (50 <= age < 60):

break;

case (60 <= age < 65):

break;

case (65 <= age < 70):

break;

case (70 <= age < 75):

break;

case (age >= 75):

break;

}

} else if (100000 <= beneAmt < 125000) {

switch (true) {

case (age < 30):

break;

case (30 <= age < 40):

break;

case (40 <= age < 50):

break;

case (50 <= age < 60):

break;

case (60 <= age < 65):

break;

case (65 <= age < 70):

break;

case (70 <= age < 75):

break;

case (age >= 75):

break;

}

}


• You would probably be best off using a table lookup. Here is an example of how you would use this in javascript: coderwall.com/p/6e7rea
– phantom
Commented Oct 30, 2014 at 17:25

I think the main improvement to this code would be to separate the definition of the premium lookup table from the logic that finds the premium for a given benefit and age, for example, using an Object-Oriented design. Doing so will simplify changes to the table and make the code easier to test and debug.

For example, consider the usage below that makes the table itself an object mapping benefit and age ranges to premium values:

var premiumTable = new PremiumTable({
'[50000, 75000)': {  // 50k <= benefit < 75k
'     30)':  2.00, //          age <  30
'[30, 40)':  2.50, //    30 <= age <= 40
'[40, 50)':  5.00, //    40 <= age <= 50
// ...
'[75     ': 35.00, //    75 >= age
},
'[75000, 100000)': {
// ...
},
// ...
});



Now you can implement the valueForBenefitAndAge method in a way that can be unit tested and changes to the premium table are localized to the initializer object rather than being related directly to the code itself.

Moreover, the PremiumTable constructor function can validate the premium table input object based on rules that will be easier to encode than using your example code. Additionally, the table could be loaded as a separate resource to further isolate the code that applies the logic from the premium table values themselves.