如何获得箭头函数的主体作为字符串? [英] How to get an arrow function's body as a string?

查看:70
本文介绍了如何获得箭头函数的主体作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以箭头函数{}之间的字符串形式获取代码?

How to get code as string between {} of arrow function ?

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

 };

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

If it is easy to parse body of simple function : myFn.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1]; is enough . However, Arrow function does not contains function keyword in its definition .

推荐答案

这是我的尝试:

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));

它可能比需要的更为冗长,因为我尝试对空白留出大手笔.另外,如果有人知道如何跳过第二遍,我将非常高兴.最终,我决定不进行任何修剪,将其留给调用方.

It's probably more verbose than it needs to be because I tried to be generous about white space. Also, I'd be glad to hear if anyone knows how to skip the second pass. Finally, I decided not to do any trimming, leaving that to the caller.

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

Currently only handles simple function parameters. You'll also need a browser that natively supports arrow functions.

这篇关于如何获得箭头函数的主体作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆