Ruby-like $.inject for jQuery

Posted on September 24, 2012

I've wanted something like this for some time so I wrote it.


    $.extend($, {
        inject: function(source, accumulator, iteratorFunction) {
            $.each(source, function(index, value) {
                accumulator = iteratorFunction.call(source, accumulator, index, value);
            });

            return accumulator;
        }
    });

Use like:


> $.inject([{"id":"48hi4ji4jf93j94", "zip": "zap"}, {"id":"kofdj93j9fj3f9jf9", "foobar": "zoobar"}], {}, function(hash, i, v){ hash[v.id] = v; return hash; });
Object
  48hi4ji4jf93j94: Object
    id: "48hi4ji4jf93j94"
    zip: "zap"
  kofdj93j9fj3f9jf9: Object
    foobar: "zoobar"
    id: "kofdj93j9fj3f9jf9"

Or...


> $.inject([1,2,3,4], 0, function(total, i, v){ return total + v; });
10

Definitely inspired by the Prototype implementation.

comments powered by Disqus