[TOD] The most compact Array.prototype.indexOf

The TOD is a JavaScript standard Array indexOf prototype implementation.

I know this is a basic trick but many times useful in IE too:

Array.prototype.indexOf=function(o,i){for(var j=this.length,i=i<0?i+j<0?0:i+j:i||0;i<j&&this[i]!==o;i++);return j<=i?-1:i}

That's all ... in the most compact way ... but what about most compact lastIndexOf prototype?

Array.prototype.lastIndexOf=function(o,i){var s=this,r=s.reverse().indexOf(o,i);s.reverse();return r}


Update
Thanks to Laurent, the most compact lastIndexOf should be this one:

Array.prototype.lastIndexOf=function(o,i){return this.slice(0).reverse().indexOf(o,i)}

Probably one slice instead of two reverse should be a better choice? I'll test them :-)

Performances? Good enough ... Compatibility? IE4 or greater!

Comments

Popular posts from this blog

8 Things you should not be afraid of as a Developer

News

Why REST is so important