In this lesson we'll look at how you can use Ramda's unfold
function to generate a list of values based on an initial seed.
[00:01] I'm requiring Ramda, and I've pulled in the unfold and curry functions. I want my result to be an array of numbers from 1 to 20, and for that I'm going to use unfold. Unfold takes two arguments. It's going to take a function, which we'll define in a moment, and it's going to take a seed value. I'm going to start with 1.
[00:19] Let's define our function. I'm going to define a constant, and I'm going to call it to20, because we want to go from 1 to 20. Our function is going to receive a number which we'll call n. If n is greater than 20, we're going to want to return false, which is going to stop adding values to our result.
[00:40] Otherwise, we want to deal with adding a value to our result. The way unfold is going to handle this, is it expects to receive an array with two items. The first item is the values you add to the result, which in this case is just going to be our number, so we want 1 to be included as part of our result.
[00:57] Then it's the next seed value that's going to get passed back into this function as n. In our case, we're just going up by one, so we want to add n + 1. Now that we have that defined, I can drop down here, and I can replace this placeholder with our actual to20 function. I can save this.
[01:16] Then I'll jump into the terminal, run it, and you'll see that our result is an array with the numbers 1 through 20. I can make this a little bit more flexible. I'm going to rename this, and we'll call it throughNBy1.
[01:29] What I'm going to do is, I'm going to add a second parameter here I'll call limit. We're going to take limit and our number, and then we'll replace this check with limit. Then we can curry this. I'll wrap a call to curry around this entire function. Then I can come down here, and I can call throughNBy1, and say this time I want numbers from 1 to 15.
[01:59] I can save that, jump back into the terminal, and this time I'll get an array with 1 through 15. If I come back over here and I change my seed value, let's say I want to start at 3, then you'll see our range has been updated. Of course we're not limited to just going up by 1. I can duplicate this line, and let's say I wanted to go through n, we'll call this one base2.
[02:25] All I'm going to do here is I'm going to accept a limit, and return a new function that will take my number. This time, instead of seeding the next call to the function with n + 1, I'm going to do n * 2 and we'll just comment that old one out. This time I can call unfold using throughNBase2.
[02:46] Let's say I want to go up to 256. We'll start at 2. We'll save this. I'll jump into the terminal. When I run it, we get back an array with the values you would expect.