如何将箭头函数的主体作为字符串?

时间:2016-07-19 08:59:41

标签: regex reflection ecmascript-6 arrow-functions

如何在箭头函数的{}之间获取代码作为字符串?

var myFn=(arg1,..,argN)=>{
         /**
          *Want to parse
          * ONLY which is between { and }
          * of arrow function 
         */ 

 };

如果很容易解析简单函数的正文:myFn.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];就足够了。但是,Arrow函数在其定义中不包含function关键字。

2 个答案:

答案 0 :(得分:1)

这是我的尝试:

function getArrowFunctionBody(f) {
  const matches = f.toString().match(/^(?:\s*\(?(?:\s*\w*\s*,?\s*)*\)?\s*?=>\s*){?([\s\S]*)}?$/);
  if (!matches) {
    return null;
  }
  
  const firstPass = matches[1];
  
  // Needed because the RegExp doesn't handle the last '}'.
  const secondPass =
    (firstPass.match(/{/g) || []).length === (firstPass.match(/}/g) || []).length - 1 ?
      firstPass.slice(0, firstPass.lastIndexOf('}')) :
      firstPass
  
  return secondPass;
}

const K = (x) => (y) => x;
const I = (x) => (x);
const V = (x) => (y) => (z) => z(x)(y);
const f = (a, b) => {
  const c = a + b;
  return c;
};
const empty = () => { return undefined; };
console.log(getArrowFunctionBody(K));
console.log(getArrowFunctionBody(I));
console.log(getArrowFunctionBody(V));
console.log(getArrowFunctionBody(f));
console.log(getArrowFunctionBody(empty));

它可能比它需要的更冗长,因为我试图对白色空间慷慨。此外,我很高兴听到有人知道如何跳过第二次传球。最后,我决定不进行任何修剪,将其留给来电者。

目前只处理简单的函数参数。您还需要一个本机支持箭头功能的浏览器。

答案 1 :(得分:0)

我之所以寻求解决方案,是因为我不想写一个解决方案,但是我并没有被接受。对于任何对ES6 1-liner感兴趣的人,我都编写了此方法,该方法可以处理我需要的所有情况-正常功能和箭头功能。

const getFunctionBody = method => method.toString().replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '$2$3$4');