如何将箭头函数的主体作为字符串获取?
How to get an arrow function's body as a string?
如何获取箭头函数 {}
之间的字符串代码?
var myFn=(arg1,..,argN)=>{
/**
*Want to parse
* ONLY which is between { and }
* of arrow function
*/
};
如果简单函数的主体很容易解析:myFn.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
就足够了。但是,箭头函数在其定义中不包含 function
关键字。
这是我的尝试:
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));
它可能比需要的更冗长,因为我试图对白色大方 space。另外,我很高兴听到是否有人知道如何跳过第二遍。最后,我决定不做任何修剪,留给调用者。
目前只处理简单的函数参数。您还需要一个本身支持箭头功能的浏览器。
我是来寻找解决方案的,因为我不想写一个解决方案,但我并没有被接受的答案说服。对于任何对 ES6 1-liner 感兴趣的人,我编写了这个方法,它处理我需要的所有情况——普通函数和箭头函数。
const getFunctionBody = method => method.toString().replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '');
如何获取箭头函数 {}
之间的字符串代码?
var myFn=(arg1,..,argN)=>{
/**
*Want to parse
* ONLY which is between { and }
* of arrow function
*/
};
如果简单函数的主体很容易解析:myFn.toString().match(/function[^{]+\{([\s\S]*)\}$/)[1];
就足够了。但是,箭头函数在其定义中不包含 function
关键字。
这是我的尝试:
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));
它可能比需要的更冗长,因为我试图对白色大方 space。另外,我很高兴听到是否有人知道如何跳过第二遍。最后,我决定不做任何修剪,留给调用者。
目前只处理简单的函数参数。您还需要一个本身支持箭头功能的浏览器。
我是来寻找解决方案的,因为我不想写一个解决方案,但我并没有被接受的答案说服。对于任何对 ES6 1-liner 感兴趣的人,我编写了这个方法,它处理我需要的所有情况——普通函数和箭头函数。
const getFunctionBody = method => method.toString().replace(/^\W*(function[^{]+\{([\s\S]*)\}|[^=]+=>[^{]*\{([\s\S]*)\}|[^=]+=>(.+))/i, '');