user6427229
user6427229

Reputation:

Currying with filter

let dragons = [
    { name: "Test1", power: "Fire" },
    { name: "Test2", power: "Lightning" },
    { name: "Test3", power: "Fire" },
    { name: "Test4", power: "Fire" },
    { name: "Test5", power: "Speed" },
    { name: "Test6", power: "Fly" }
];

let hasPower = power =>
    obj => 
        obj.power === power

let fireDragons = dragons.filter(hasPower("Fire"));

I get the currying part, but what I don't get is how the currying function gets passed obj from filter, can someone explain that to me?

Upvotes: 2

Views: 934

Answers (1)

Rahul Gandhi
Rahul Gandhi

Reputation: 1095

Before understanding the code you shared, let's first learn the syntax of the filter function.

var newArray = arr.filter(callback(currentValue[, index[, array]])[, thisArg])

callback Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise, taking three arguments: element, index and the array itself. thisArg is optional, though.

Now, let's try to understand the code.

let hasPower = power =>
    obj => 
        obj.power === power

The function hasPower can be updated as:

let hasPower = function (power) {
    return function (obj) {
        return obj.power === power;
    }
}

Just keep in mind, whenever hasPower would be executed, it will simply return a function (which would be executed later) and will have access to the power variable. (Read more: Closure)

and now the fireDragons,

let fireDragons = dragons.filter(hasPower("Fire"));

You are passing a function as a parameter to the filter function (invoking it as well).

When this line of code is executed, the function hasPower("Fire") would be executed first and whatever is returned from that function would be passed to the filter as the callback function.

Basically, it would become something like:

let fireDragons = dragons.filter(function (obj) {
    // Having access to the `hasPower` variable which is "Fire" in your case.
    return obj.power === power;
});

or exactly like this: enter image description here

Always try to debug in the developer tools to understand how the code works and feel free to replace the arrow functions with regular ones to make it more readable/understandable.

Upvotes: 3

Related Questions