Reputation: 79
When this method is called with knownScore = 70, newScore = 70, depth = 1, it returns 3535 !!!!! How is this possible?
this.weightedAvg = function(depth, knownScore, newScore) {
if ((knownScore > 100) || (knownScore < -100)) return newScore;
else return Math.round((depth*knownScore + newScore)/(depth + 1));
};
When called with values 35, 70, 2, it returns 2357! Any help please?
Upvotes: 1
Views: 57
Reputation: 1570
You need to parse your var to number like this:
var number1 = Number(n);
You are passing string so he do "2" + "35" + "70" instead of 2 + 35 + 70 !
Upvotes: 2
Reputation: 27823
The value of newScore you're passing to the function is a string. You should make sure they are all numbers. This code will work (notice the + sign that converts newScore to a number):
this.weightedAvg = function(depth, knownScore, newScore) {
if ((knownScore > 100) || (knownScore < -100)) return newScore;
else return Math.round((depth*knownScore + +newScore)/(depth + 1));
};
More details:
70 + '70' // this is string concatenation instead of addition, results in 7070
The result is converted to a number when it is divided by 2:
'7070'/2 // converts to number, resulting in 3535
Upvotes: 3