Seeeyonnn
Seeeyonnn

Reputation: 325

Functional Javascript example of higher-order functions using plucker, reduce and finder functions

I'm going through the book Functional Javascript by Michael Fogus. In chapter 4, he creates a function, titled finder, which utilizes reduce. I'm having difficulty grasping the implementation of this function...

function finder(valueFun, bestFun, coll){
    return _.reduce(coll, function(best, current){
        var bestValue = valueFun(best);
        var currentValue = valueFun(current);

        return (bestValue === bestFun(bestValue, currentValue)) ? best : current;
    });
}

(Note that he uses the Underscore.js library in his book)

Anyways, he uses the finder-function in the following example:

var people = [{name: "Fred", age: 65}, {name: "Lucy", age: 36}];

**finder(plucker('age'), Math.max, people);**

Where the plucker function is defined as:

function plucker(field){
    return function(obj){
        return (obj && obj[field]);
    }
}

(plucker is supposed to return the value of a key)

I'm going through the code line by line, but I'm struggling when I come across the reduce-function w/in the finder-function definition. What I don't understand is

valueFun(best)

and valueFun(current)

what are the values of best and current, respectively, with each iteration through the reduce-function? My understanding is that valueFun is the plucker function. But he gives plucker the argument 'age' already, so then what does best and current represent?

If you're answering this, I'd really appreciate if you outlined how you arrive at your answer so that I see the values going through the finder function step by step. THANKS!

Upvotes: 2

Views: 270

Answers (1)

Mike Bell
Mike Bell

Reputation: 1396

One thing that new JavaScript coders struggle with is how often functions get passed around, both as arguments to other functions and as returns from other functions.

My understanding is that valueFun is the plucker function.

Not quite. When he invokes finder(plucker('age'), Math.max, people); the first argument to finder is the result of plucker('age'). In effect, this is the function function(obj){ return (obj && obj['age']);}

To make this a bit more explicit, we could do something like this:

    var ageGetter = plucker('age');
    finder(ageGetter, Math.max, people);

So essentially plucker('age') (valueFun) is just a function that returns the age property of an object. bestFun is the Math.max function, which just returns the higher of two numbers. In each iteration of the _.reduce function, he's comparing the age value of the current object with the highest existing value and returning the greater of the two.

If it's not covered in that book, you'll want to read about closures in JavaScript, as that is extremely relevant to this example.

Upvotes: 4

Related Questions