tag:www.rhnh.net,2008:/injectInject - Xavier Shay's Blog2008-12-28T17:16:03ZEnkiXavier Shaynotreal@rhnh.nettag:www.rhnh.net,2008:Post/7912008-12-28T17:16:03Z2008-12-28T17:16:03Zinject 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’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 // => [1, 4, 9]<tt>
</tt></pre></td>
</tr></table>
<p><a href="http://github.com/xaviershay/jquery-enumerable/tree/master">It’s on github</a>. It deliberately doesn’t have the kitchen sink – fork and add methods you need, there’s enough code it should be obvious the correct way to do it.</p>
<p>As an aside, it’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: “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”. Bit of a mouthful eh.</p>
<p>Post your improvements in the comments.</p>