Skip to content

Instantly share code, notes, and snippets.

@cedricvidal
Created November 25, 2012 17:58
Show Gist options
  • Save cedricvidal/4144576 to your computer and use it in GitHub Desktop.
Save cedricvidal/4144576 to your computer and use it in GitHub Desktop.
Some Underscore.js extensions
/*
* @author <a href="mailto:cedric at vidal dot biz">Cedric Vidal</a>
*/
_.mixin({
and : function() {
var funcs = arguments;
return function() {
var args = arguments;
return _.all(_.map(funcs, function(f) {return f.apply(this, args);}), _.identity);
};
},
array : function(object) {
return _.isArray(object) ? object : [object];
},
// Asynchronous version of _.reduce
// _.reduceAsync([1, 2, 3], function(memo, num, cb){ cb(memo + num); }, function(result) {console.log(result)}, 0);
reduceAsync : function(obj, iterator, callback, memo, context) {
if (obj == null) obj = [];
var first = _.first(obj);
if(first) {
var rest = _.rest(obj);
iterator.call(context, memo, first, function(memo) {
_.reduceAsync(rest, iterator, callback, memo, context);
}, 0, rest);
} else {
callback(memo);
}
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment