const
sumOfSquares
=
newSummer
(
x
=>
x
*
x
);
const
sumOfCubes
=
newSummer
(
x
=>
Math
.
pow
(
x
,
3
));
sumOfSquares
([
1
,
2
,
3
]);
// returns 14
sumOfCubes
([
1
,
2
,
3
]);
// returns 36
This technique—where we have taken a function with multiple
arguments and converted it to a function with a single argument—
is called currying, after its developer, American mathematician
Haskell Curry.
The applications for returning a function from a function are often deep and compli‐
cated. If you want to see more examples of this, look at middleware packages for
Express or Koa (popular JavaScript web development frameworks); more often than
not, middleware is a function that returns a function.
Recursion
Another common and important way that functions are used is recursion. Recursion
refers to a function that calls itself. This is a particularly powerful technique when the
function does the same thing with progressively smaller sets of input.
Let’s start with a contrived example: finding a needle in a haystack. If you were con‐
fronted with a real-life haystack and had to find a needle in it, a viable approach
might be this:
1. If you can see the needle in the haystack, go to step 3.
2. Remove a piece of hay from the haystack. Go to step 1.
3. Done!
Basically you’re whittling the haystack down until you find the needle; in essence, this
is recursion. Let’s see how we would translate this example into code:
function
findNeedle
(
haystack
) {
if
(
haystack
.
length
===
0
)
return
"no haystack here!"
;
if
(
haystack
.
shift
()
===
'needle'
)
return
"found it!"
return
findNeedle
(
haystack
);
// haystack has one fewer element
}
findNeedle
([
'hay'
,
'hay'
,
'hay'
,
'hay'
,
'needle'
,
'hay'
,
'hay'
]);
The important thing to note in this recursive function is that it is handling all the
possibilities: either
haystack
is empty (in which case there’s nothing to look for), the
needle is the first element in the array (done!), or it’s not (it’s somewhere in the rest of
the array, so we remove the first element and repeat the function—remember that
Array.prototype.shift
removes the first element from the array in place).
196 | Chapter 13: Functions and the Power of Abstract Thinking