Tip 35: Combine Currying & Array Methods for Partial Application
In this tip, you’ll learn to lock in variables with partial application of functions.
In the previous tip, you saw how you can give parameters a single responsibility with higher-order functions and partial application. It solved the problem of having unrelated parameters, but it didn’t solve the problem of using the same parameters over and over. You still passed in the same parameters multiple times.
Avoiding parameter repetition
With higher-order functions, you can avoid repetition by creating a new function with values you lock-in once and use later. When you return a higher-order function, you don’t have to invoke it right away. After you invoke it once, you have another pre-made function that you can use over and over. It’s like you wrote it with the argument hard-coded.
To reuse the building
and manager
from the previous tip, you can assign the
return value from the first function call to a variable. You now have a prebuilt
function with some information locked in place.
Invoking it once and reusing the captured parameters is no different from declaring a function knowing the inside variables ahead of time. These are equivalent.
Get hands-on with 1400+ tech skills courses.