Skip to content

Instantly share code, notes, and snippets.

@jsmecham
Created October 17, 2011 15:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsmecham/1292846 to your computer and use it in GitHub Desktop.
Save jsmecham/1292846 to your computer and use it in GitHub Desktop.
Useful Underscore.js Extensions
(function() {
//
// Iterates over an array of numbers and returns the sum. Example:
//
// _.sum([1, 2, 3]) => 6
//
_.sum = function(obj) {
if (!$.isArray(obj) || obj.length == 0) return 0;
return _.reduce(obj, function(sum, n) {
return sum += n;
});
}
})();
@alioguzhan
Copy link

you should pull request for this. very useful.

@iVoteSize
Copy link

With mixin:

_.mixin( {
    sum: function ( Object ) {
        if (
                !$.isArray( Object ) ||
                Object.length == 0 ) {
            return ( 0 )
        }
        return (
            _.reduce(
                Object, function ( Sum, Number ) {
                    return ( Sum += Number )
                } ) )
    }
} )

.... allows for _([1, 2, 3]).sum() => 6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment