I am trying to write a function that converts something into a function. The function should work as follows:
- Check if it is already a function, and if so returns it easily.
- Check if this is a string, and if so, then there is a global function with that name, if so returns.
- Check if it is possible to evaluate the string, and if so, return the lambda (anonymous) function that evaluates the string.
- If all previous attempts to convert a value to a function fail, return the lambda (anonymous) function that returns the value. This is also how I handle all other types of variables (numbers, zero, undefined, booleans, objects and arrays).
function canEval(str){
try { eval(str); } catch (e){ return false; }
return true;
}
function toFunc(v){
if(typeof(v) == "function") return v;
if(typeof(v) == "string"){
if(
window[v] != undefined &&
typeof(window[v]) == "function"
) return window[v];
if(canEval(v))
return function(){eval(v)};
}
return function(){return v;};
};
, canEval , , ( ) . , , - , () , .
, ( ) ? , , (), ?