In the previous lesson we created this recursive function, get tasks. This implementation, though, has some problems. First of all, because we have this array defined outside the function, and then we push items onto it from inside the function, it means that every time this runs now it relies on the external state of this array.
Also, because this function does not return a value directly, it makes it extremely hard to test. Really what we want is to be able to assign this tasks variable to the result of calling this function. To do this we'll need to refer to how this works. To make your return of value we can swap for each for reduce. The signature for reduce is the previous value and the next value.
On the first run-through, previous won't equal anything yet. We need to seed for the reduce function. We'll call that initial. We'll actually pass that in as the first argument to the get tasks function.
This means that when we call it for the very first time we can send in an empty array. Our goal is to get an array out of the other end of this function and it will be the result of building up from this empty array. We call get tasks with an empty array and our input. The reduce function gets called on the input, passing in the initial value.
The first time it runs, previous will be equal to this empty array and next will be equal to build. We do a very similar thing to the previous example, only this time we're looking at the next value, which is going to be each item of the array. We do the same check as before.
But now, whereas previously we just called the task again and allowed the external array to be mutated, we instead need to return the result of this function and pass along not the initial value but the previous value. To actually build up that previous value where we previously pushed onto that tasks array we will instead return the previous value, which will be an array. We'll conquer onto that the current item.
If we run this you can see we get exactly what we expected. The major difference here is that we are not relying on any external state and we have a return value from get tasks. This is now what we call a pure function, in that it has no side effects and calling it with the same values will always produce the same results.
This has big implications for things such as testing and the ability to share this function across your application....