Create Reusable Functions with Partial Application in JavaScript

Kyle Shevlin
InstructorKyle Shevlin
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 6 years ago

This lesson teaches you how arguments passed to a curried function allow us to store data in closure to be reused in our programs and applications. Since each argument, except for the final one, returns a new function, we can easily create reusable functions by supplying some of these arguments beforehand, and sharing these partially applied functions with other parts of our codebase. In this lesson, we'll create a curried function to fetch requests from an API that uses partial application to create reusable functionality.

Instructor: [00:00] A partial application occurs whenever a curried function has some but not all of its function applied. To demonstrate this, we'll create a curried getFromAPI function. It'll receive a base URL, an endpoint, and a callback to be called once we've received our data from the request.

[00:19] We'll use nodeFetch to fetch our data. Our URL will be a combination of the base URL and the endpoint. We'll turn our response into JSON. After that, we'll call our callback on our data, and we'll catch any errors for good measure.

[00:38] Now let's partially apply a base URL. One public API we can use is the GitHub API. Now we have a partially applied GitHub function that we can pass different endpoints to. Let's create functions to the users endpoint and the repositories endpoint.

[00:57] Now we have two new functions each that have partially applied the same base URL, but have partially applied different endpoints. The last thing we can supply to them is a callback which will trigger the fetch. Let's use the getGithubUsers function and supply different callbacks to each one.

[01:17] For the first one, let's log out the user login names. The main benefit of partial application is our ability to delay the evaluation of a function while still supplying some of the arguments to be stored and reused throughout our application. For the second one, let's log out the user avatar URLs. You can see we have avatar URLs and we have user names.