tag:www.rhnh.net,2008:/inject Inject - Xavier Shay's Blog 2008-12-28T17:16:03Z Enki Xavier Shay notreal@rhnh.net tag:www.rhnh.net,2008:Post/791 2008-12-28T17:16:03Z 2008-12-28T17:16:03Z inject and collect with jQuery <p>You know, I would have thought someone had already made an enumerable plugin for <a href="http://jquery.com">jQuery</a>. Maybe someone has. Mine is better.</p> <ul> <li>Complete coverage with screw-unit</li> <li>Interface so consistent with jQuery you&#8217;ll think it was core</li> </ul><table class="CodeRay"><tr> <td class="line_numbers" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<tt> </tt>2<tt> </tt>3<tt> </tt>4<tt> </tt></pre></td> <td class="code"><pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }">squares = $([1,2,3]).collect(function () {<tt> </tt> return this * this;<tt> </tt>});<tt> </tt>squares // =&gt; [1, 4, 9]<tt> </tt></pre></td> </tr></table> <p><a href="http://github.com/xaviershay/jquery-enumerable/tree/master">It&#8217;s on github</a>. It deliberately doesn&#8217;t have the kitchen sink &#8211; fork and add methods you need, there&#8217;s enough code it should be obvious the correct way to do it.</p> <p>As an aside, it&#8217;s really hard to spec these methods concisely. I consulted the rubyspec project and it turns out they had trouble as well, check out this all encompassing spec for inject: &#8220;Enumerable#inject: inject with argument takes a block with an accumulator (with argument as initial value) and the current element. Value of block becomes new accumulator&#8221;. Bit of a mouthful eh.</p> <p>Post your improvements in the comments.</p>