Created
June 1, 2012 17:39
-
-
Save schmerg/2853910 to your computer and use it in GitHub Desktop.
Demo of a hacky def function for a lambda-like syntax in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// def(function() { $[0]+$[1] }) --> $ is a real array of args, adds a return | |
var def = function(f) { | |
// Another option is like this so $0, $1 etc | |
//return eval("(" | |
// +(f.toString() | |
// .replace(/\$_/g, "arguments[0]") | |
// .replace(/\$[\d+]/g, function(r,num) { return "arguments["+num+"]" }) | |
// .replace(/\) { /, ") { return ") | |
// )+")"); | |
// Hacks around for trailing ; issue, and suffers from closure issues (when we eval here | |
// any local symbols have vanished) but the idea is good... see caterwauljs.org for the | |
// real thing (https://github.com/spencertipping/caterwaul) !! | |
// Inspiration from http://www.spencertipping.com | |
// Note [\s\S] matches any char, whereas '.' won't match a \n | |
return eval(("("+f+")").replace(/\) \{([\s\S]*)\}\)$/, function(s,m) { | |
return (") {" | |
+"var $ = Array.prototype.slice.call(arguments,0), $_ = $[0];" | |
+"return ("+m.replace(/;\s+$/, "")+"); })"); | |
})); | |
}; | |
var add2 = def(function() { $[0] + $[1] }); | |
var sum = def(function() { $_.reduce(add2, 0) }); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that you can still name parameters if you want
add2 = def(function(x,y) { x+y; })
and you can avoid breaking closures if you don't mind moving the eval outside of def() (ie this is tailored to my personal taste, feel free to fiddle)