Inspired by this article on curry functions I was trying to chain them and came up with this solution. I'm not sure about the mixin though since I somehow feel that lodash might have such a function allready. If so, what is this function called?
var _ = require('lodash');
var get = _.curry(function(property, object) {return object[property]});
var map = _.curry(function(fn, objects){ return objects.map(fn) });
var json = {
"user": "hughfdjackson",
"posts": [
{ "title": "why curry?", "contents": "..." },
{ "title": "prototypes: the short(est possible) story", "contents": "..." }
]
}
_.mixin({
then:function(input, fn) {return fn(input);}
});
_(json)
.then(get('posts'))
.then(map(get('title')))
.tap(console.log)
In Hugh Jackson's (excellent!) article, the then
functions would presumably be coming from a Promise library, probably tied to an AJAX call. So you wouldn't need to do it yourself, if you were starting there. Mixing it into _
like that does seem odd.
Lo-Dash and Underscore will allow you to do this with their curry
functions. Some newer libraries such as Ramda and FKit do this automatically. Their versions of get
and map
are already curried, and designed to be used this way. (Disclosure: I am one of the authors of Ramda)