if (s = 'f') {
It seems that you are trying to do some comparison here (considering this is in a for
-loop). However, you are using the assignment operator so this will always evaluate to true
)
if (s == 'f') {
if (weightFemale.hasOwnProperty(i)) {
var m = weightFemale[i][0],
l = weightFemale[i][1],
s = weightFemale[i][2];
return getcalc( m,l,s );
}
}
else {
if (weightMale.hasOwnProperty(i)) {
var m = weightMale[i][0],
l = weightMale[i][1],
s = weightMale[i][2];
return getcalc( m,l,s );
}
}
These two inner if
-statements are virtually identical, all except for weightMale
and weightFemale
. Duplicating code is bad practice, so I recommend that you use a ternary operator to decide whether or not you are going to use weightMale
or weightFemale
. Then, just execute using this new information.
Here is the ternary operator:
var weight = s == 'f' ? weightFemale : weightMale;
Now that you have this new weight
variable, you can just use that when running the rest of the code, rather than the specific weightMale
or weightFemale
:
if (weight.hasOwnProperty(i)) {
var m = weight[i][0],
l = weight[i][1],
s = weight[i][2];
return getcalc( m,l,s );
}
The same exact concept can be applied to the height
section.
This is a rather strange way to see if an index exists in an array:
if (weightFemale.hasOwnProperty(i)) {
I think it would be better to check against the length of the array like this:
if (i < weightFemale.length) {
This looks better because then someone is just quickly looking over your code won't get tripped up and think that weightFemale
is actually an object (yeah, everything is an object in JavaScript; I know. You get the point right?)
Here is what the code looks like now:
function calculate(type, j, value, s) {
for (var i = j; i > 4; i--) {
if (type == 'weight') {
var weight = s == 'f' ? weightFemale : weightMale;
if (i < width.length) {
var m = weight[i][0],
l = weight[i][1],
s = weight[i][2];
return getcalc( m,l,s );
}
}
else if (type == 'length') {
var length = s == 'f' ? lengthFemale : lengthMale;
if (i < length.length) {
var m = length[i][0],
l = length[i][1],
s = length[i][2];
return getcalc( m,l,s );
}
}
}
}
return false;
}