r/javascript • • Jul 19 '16

JavaScript Functors Explained

http://freecontent.manning.com/javascript-functors-explained/
5 Upvotes

14 comments sorted by

View all comments

3

u/ggolemg2 Jul 19 '16

Can anyone give an example in a non-FP es5 way?

2

u/inmatarian Jul 19 '16

Start with this function:

function double(x) { return x * 2; }

Now, image we have an object that's this:

{
    "awesomeness": 10
}

Now lets say you wanted to get the double of the awesomeness of an object, that's easy, var thingsDoubleAwesome = double(thing.awesome);

However, you really want it to be in another object with the awesomeness field filled, so you do this:

function doubleAwesomeness(container) {
    return { "awesomeness": double(container.awesomeness) };
}
var thingsDoubleAwesome = doubleAwesomeness(thing);

An abstract reusable version of this looks like so:

function applyAwesomeness(action, container) {
    return { "awesomeness": action(container.awesomeness) };
}
var thingsDoubleAwesome = applyAwesomeness(double, thing);

And a functor just makes this a partial function that returns another:

function applyAwesomeness(action) {
    return (container) {
        return { "awesomeness": action(container.awesomeness) };
    };
}
var doubleAwesomeness = applyAwesomeness(double);
var thingsDoubleAwesome = doubleAwesomeness(thing);