I am attempting to write a function that will convert anything into a function. The function should work as follows:
- Check to see if it already is a function and if so just returns it.
- Check to see if it is a string and if so is there a global function with that name, if so return that.
- Check to see if the string can be evaluated and if so return a lambda (anonymous) function that evaluates the string.
- If all previous attempts to convert the value into a function fail, return a lambda (anonymous) function that returns the value. This also is how I handle all other variable types (numbers, null, undefined, boolean, 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;};
};
The problem with this code is that canEval
actually evaluates the code, in some circumstances I do not want the code (in a string) to run more than once. Currently it evaluates the string to see if there are any errors, and if not it returns the evaluated code (string) as a function, to then be ran again at a later date.
Is there any way I can test to see if the code can be evaluated (without errors) without actually running the code? or run it isolated so that what happens in the evaluated code (string) doesn't take ANY affect on the current file?