What’s the shortest way (characters) of creating a “new function” alias.
Basically this is for code golf and minifying code beyond reason.
So when you usually would write:
a=function(a,b,c){return a+b+c;}
You could write something like (also let’s abstract return keyword as well with global variable R):
a=$("a,b,c","R=a+b+c")
a=$(a,b,c){R=a+b+c}
(Not sure if the second one is possible.)
For the first example the best I’ve come up with is:
$=function(a,b){return new Function(a,"R=0;"+b+";return R")}
Both the sizes (usage, declaration) matter but usage size is more important.
I don’t think
new Function()is of viable use for most functions even without performance concerns because unlikefunction() {}no closure is created. The compiled function will only have access to its own local scope and the global object. Think about that for a second. Javascript without closures is like Java without classes or C without pointers. Clearly everything would break.Anyways, if you only intend to use this alias for short lambada like expressions that don’t need clousers, one obvious way to make things even more terse is to leave off the parameters deceleration. Simply assume that
a = arguments[0]; b = arguments[1];etc…Another way would be to automatically return the value of the last expression, instead of needing it to be explicitly declared
Horrifying isn’t it? This works because
eval()…well it returns the value of the last evaluated expression. Noreturnneeded. Of course this method is an even bigger hit to performance, as the code inbodyis reevaluated each time the function is called, while withnew Functionthe code is (or should be) only compiled once.Anyways performance be dammed, with the previous method your function declaration is down to this
Purdy huh? Still, I think it would look better like this
Looks like a string yes? Well…it is a sting, but in the hands of the right function, it could be evaluated as if it were a full on function literal
Now you can write
instead of
which is even better than Firefox’s Expression Closure
Try it out here: http://jsbin.com/iyogu3/edit
If only we could actually write function expressions like this without calling upon the eval monster. Really, one of my main gripes with Javascript syntax is the requirement to spam
function(){}throughout your code. Some kind of shorthand function literal syntax (not the aforementioned half-assed expression closure) that was interpreted the same as a regular verbose function literal would go a long way to making my code look a little less ridiculous. And it might help minifying a tiny bit as well.