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.
i think you missed fat arrow in "Transcript" at every 'cb' .
const getFromAPI = baseURL => endpoint => cb
const getFromAPI = baseURL => endpoint => cb =>
Curring: const add = x => y => z => x + y + z; Partial Application: const add = x => (y, z) => x + y + z; right?
@Xu, no, not really. Partial application means that you have supplied values for the arguments (but not so many that you've triggered the final argument and the evaluation of the function).
// Your curried add function for three values const add = x => y => z => x + y + z // Partially apply first value const add10 = add(10) // returns y => z => 10 + y + z // Partially apply the second value const add25 = add10(15) // returns z => 10 + 15 + z // By passing in the final argument, the last function is called and we get the result const fortyFive = add25(20) // returns 10 + 15 + 20 === 45