How to get an arrow function's body as a string?

心不动则不痛 提交于 2020-01-05 04:20:10

问题


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 
         */ 

 };

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 .


回答1:


This is my attempt:

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.




回答2:


I came looking for a solution because I didn't feel like writing one, but I wasn't sold on the accepted answer. For anyone interested in an ES6 1-liner, I wrote this method, which handles all the cases I needed - both normal functions and arrow functions.

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


来源:https://stackoverflow.com/questions/38453881/how-to-get-an-arrow-functions-body-as-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!