Arrow Function PolyFill and LINQ JS $ syntax
by Luis Perez
JavaScript
var g_arrowCache = Object.create(null);
function arrow(expression) {
function cache(cache, key, getValueFunc) {
var value = cache[key];
if(value === undefined) {
value = getValueFunc(key);
cache[key] = value;
}
return value;
}
function arrowImpl(expression) {
// This function is a polyfill for proposed "arrow functions" in JavaScript.
// It also adds an additional sytax using $ for single variables like JS LINQ
// does.
//
// Examples:
// o => o.age
// (sum, o) => sum + o.charge
// sum, o => sum + o.charge
// $.age
if(expression.search(/\bthis\b/) != -1) throw "'this' not supported";
if(expression.search(/(^|[^\$\.])\$([^\$]|$)/) != -1) {
var indexOfArrow = expression.indexOf("=>");
if(indexOfArrow != -1) throw "Can't use both $ and =>";
return new Function("$", "return " + expression.trim() + ";");
}
var indexOfArrow = expression.indexOf("=>");
if(indexOfArrow == -1) throw "Expressio is missing the arrow operator =>";
var parametersString = expression.substring(0, indexOfArrow);
//console.log("DEBUG - parametersString: " + parametersString);
parametersString = parametersString.replace("(", "").replace(")", "");
//console.log("DEBUG - parametersString: " + parametersString);
var parameters = parametersString.split(",");
parameters.map(function(o) { return o.trim(); });
//console.log(parameters);
var functionBody = expression.substring(indexOfArrow + 2);
if(expression.indexOf("{") != -1) throw "Use of curly brackets for multiple statements not supported or recommended.";
if(expression.indexOf("}") != -1) throw "Use of curly brackets for multiple statements not supported or...