In JavaScript, I can check if a string can be evaluated without an actual evaluation?

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 , , ( ) . , , - , () , .

, ( ) ? , , (), ?

+4
1

- , , . , toFunc, , .

function toFunc(v){
    if(typeof(v) == "function") return v;
    if(typeof(v) == "string"){
      if(
        window[v] != undefined &&
        typeof(window[v]) == "function"
      ) return window[v];
      try {
        return new Function(v);
      }catch(e){}
    }
    return function(){return v;};
  };
Hide result

Function try-catch

+1

Source: https://habr.com/ru/post/1626358/


All Articles