Next lesson playing in 5 seconds

  • Overview
  • Transcript

3.1 Functional Filter

Now that we have a declarative beer filtering function that takes a callback, let's make it generic so it can be used in any filtering situation. This lesson will demonstrate just how easy this is. Almost as if it was planned that way...

3.1 Functional Filter

Okay, so this is the part of this course that I've been most excited about. We're going to finally start building some of our own functional utilities. So, as we've been going, we've been trying to make our functions pure, and also generic, so that they don't have to know anything about their surroundings. They can just work. And one benefit of this doing this, which is a very functional thing to do, is that we can start to remix our functions. We can make general utilities that we can reuse across all of our projects. The first one we're gonna make is just a generic filter method. We've already been doing a lot of filtering, so I think you'll find this is gonna be a pretty easy one to start with. The reason is, I'm gonna go ahead and make a generic filter method. Let's change filter beers to say filter, let's make beers turn into the word collection. Then instead of filtered beers, we'll just have a filtered array. And then we need to change our reference to beers to collection and ta-da, we're done. All we're doing is taking a collection of anything and a callback. We're making a filtered array, looping over the collection, applying the callback to each item. If it returns true, we push that onto our filter. Oh, and one more reference here. And then we return the filtered list. So this now is completely generic. We can also make this makeFilter generic by applying the same kind of thing. So, collection. Obviously we don't wanna call the filter in a function, so we have to change that. We can pass our collection here. And we'll just call this item, and then this is item[property] equals the value. And now this method is also generic. We can reuse this, as long as we wanna make a filter that is one property to one value, true or false. And so we're already using that this way. We don't have to change these at all. But we are calling filter directly down here, so let's just make sure we change this. And then we will have to do one more thing, because we actually have this var filter right here which is going to, in this scope, overwrite the filter function. So instead we're just going to call this the filterName and then we'll switch on the filterName. And now filter itself is still a reference to the function up there. So let's just go back to the browser to just verify for sure that this still works. Refresh and run through all our filters, and everything's working just like it was before but now with nice, generic, functional filter. So that's filter. In the next video, we'll expand on this concept of creating more functional utilities.

Back to the top