stringify-parameters
Version:
Stringifies function's parameters definition
30 lines (23 loc) • 975 B
JavaScript
;
const unpackString = require('unpack-string');
function stringifyParameters(fn) {
const asyncFunctionConstructor = Object.getPrototypeOf(async function(){}).constructor;
if (!fn || (fn.constructor !== String && fn.constructor !== Function && fn.constructor !== asyncFunctionConstructor)) {
return;
}
let fnString = fn.toString().replace(/^\s+|\s+$/g, '');
if (!fnString) {
return;
}
const isDeclaredWithFunctionKeyword = /^function/i;
const isNotArrowFunction = /^[^\s=>]+\(/i;
// Is an Arrow function with a parameter declared without parenthesis and with no default value
if (!isDeclaredWithFunctionKeyword.test(fnString) && !isNotArrowFunction.test(fnString)) {
let arrowWithoutParenthesis = fnString.match(/^(.*?)=>/);
if (arrowWithoutParenthesis) {
return unpackString(arrowWithoutParenthesis[1]).replace(/^\s+|\s+$/g, '');
}
}
return unpackString(fnString).replace(/^\s+|\s+$/g, '');
}
module.exports = stringifyParameters;