Java Reference
In-Depth Information
}
hypotenuse(3,4);
<< 5
The
hypotenuse()
function uses the
square()
function to square the numbers, rather
than hard coding
a*a
and
b*b
into the function. This means that if we find a more optimal
way to square a number, we only have to improve the implementation of the
square()
function. Or if we find an alternative way of calculating the hypotenuse (however unlikely
that is!), we could just swap the
square()
function for another.
To illustrate the point further, we can create another function called
sum()
that takes an
array as an argument as well as a callback. The callback is used to transform the value of
each item in the array using the
map()
method, and then the
reduce()
method is used
to find the sum of all items in the array:
function sum(array, callback) {
if(typeof callback === "function") {
array = array.map(callback);
}
return array.reduce( function(a,b) { return a + b });
}
The callback makes the function more flexible as it allows a transformation to be performed
on all the numbers in the array before finding the sum. This means it can be used to find
the sum of a set of numbers:
sum([1,2,3]); // returns 1 + 2 + 3
<< 6
Or the sum of a set of numbers after they've been squared (here we're using the square
function as the callback):
sum([1,2,3], square); // returns 1^2 + 2^2 + 3^2
<< 14
This function can then be used to create a
mean()
function that calculates the mean of an
array of numbers:
