Java Reference
In-Depth Information
function compareNumbers (a,b) {
if (a < b) {
return -1;
} else if (a> b) {
return 1;
} else {
return 0;
}
}
Improving the mean() Function
Earlier in the chapter we created a mean() function that would calculate the mean of any
number of arguments. We can improve on this, allowing a callback to be added as the last
argument that specifies a function to be applied to all the numbers before the mean is cal-
culated. This will allow us to work out things such as the mean of all numbers if they were
doubled or squared.
Here is the code for the improved function that accepts a callback:
function mean(values, callback) {
var total = 0;
for(var i=0, max = values.length; i < max; i++) {
if (typeof callback === "function") {
total += callback(values[i]);
} else {
total += values[i];
}
}
return total/max;
}
The next part of the code is similar to our previous mean() function. , except in the fol-
lowing if block where we check to see if the callback argument is a function. If it is,
the callback is applied to each value before being added to the total; otherwise, the total is
calculated using just the values from the array given as the first argument:
Search WWH ::




Custom Search