MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/javascript/comments/4tk8sp/javascript_functors_explained/d5iq2g6/?context=3
r/javascript • u/jrsinclair • Jul 19 '16
14 comments sorted by
View all comments
3
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);
2
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);
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);
3
u/ggolemg2 Jul 19 '16
Can anyone give an example in a non-FP es5 way?