View Single Post
Old 11-20-2012, 08:42 AM   PM User | #2
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
great point, that's very useful. i see a lot of wheel-re-invention around here.
i don't see generics used enough.

i personally think it's neat to overload the 20-something keywords and built-ins JS provides.

the newer revisions in current browsers make recycling even easier and more dynamic.
this was done by spec'ing most methods as generic.

so, if you don't like typing ".apply" all the time, pre-bake an array-expecting version using bind:


Code:
var max=Math.max.apply.bind(Math.max, 0);
now, the hot awesomeness works without the apply() making it handier to use and re-use.

Code:
var max=Math.max.apply.bind(Math.max, 0);

var myMax= max([4,7,-2,55,2,12]) ;

alert( myMax ); // shows 55
if you need to support browsers going back a couple versions behind the current, a drop-in replacement will provide enough .bind() for this pattern to work.



since we're here, i'll mention my other favorite bind, a slightly more complex snip that makes a callable that allows you create arrays from anything with a .length property, like String, domCollections, arguments, etc:

Code:
var arr=Function.prototype.apply.bind([].slice);

var myArray= arr("abcde");
alert(myArray); // shows: "a,b,c,d,e"


how about getting all the even numbers from an array without a loop or using the word "return" ?

Code:
var isEven=/./.test.bind( /[-2468](\.|$)/ );

alert(
 [1,2,3,4,5,6].filter( isEven  )  
)   //shows: "2,4,6"



ok, one more, last one i swear

i hate typing "document.createElement(this), document.createElement(that), document.createElement(blah)" all the time, my poor fingers.

Rescue my over-worked digits Function.bind():
Code:
var create=document.createElement.bind(document);

var div=create("div");
 div.className=123;
 div.id=321;
 div.appendChild(create("hr"));

 alert(div.outerHTML); // shows: "<div class="123" id="321"><hr></div>"
you can re-bind getElementsByTagName, querySelectorAll, and all those other long-winded dom methods into short callable functions.

since the JS compiler has less of an activation envelope to create, a bound function runs 10-20% faster than an unbound one. this can almost erase the typical function call overhead of 18%, and your user functions say "[native code]" when you stringify them; very cool.


@felgall - sorry about the hijacking. i was just going to mention .bind() and be on my way, but i obviously got carried away again. it happens, and i think this is good info and related to your idea, so i won't delete it.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 11-20-2012 at 08:58 AM..
rnd me is offline   Reply With Quote