Skip to content

Instantly share code, notes, and snippets.

@eser
Created September 22, 2023 08:21
Show Gist options
  • Save eser/a3d927be69bd2bdbc4c8b3ea5e1381be to your computer and use it in GitHub Desktop.
Save eser/a3d927be69bd2bdbc4c8b3ea5e1381be to your computer and use it in GitHub Desktop.
function getFunctionParametersFromString(funcStr) {
const match = funcStr.match(/(?:function.*?\(|\()(.*?)(?:\)|=>)/);
if (match && match[1]) {
return match[1].split(',').map(p => p.trim());
}
return [];
}
function getFunctionParameters(func) {
return getFunctionParametersFromString(func.toString());
}
function analyzeParameter(param) {
const decoratorMatch = param.match(/@(\w+)\(([^)]+)\)/);
const defaultValueMatch = param.match(/(.*?)=(.*)/);
const isRestOrSpread = param.startsWith('...');
let decorators = [];
if (decoratorMatch) {
const [_, decoratorName, decoratorArgs] = decoratorMatch;
decorators.push({
name: decoratorName,
args: decoratorArgs.split(',').map(arg => arg.trim())
});
}
const paramName = (isRestOrSpread ? param.substr(3) : param).trim();
if (defaultValueMatch) {
const [_, name, defaultValue] = defaultValueMatch;
return {
parameter: paramName,
defaultValue: defaultValue.trim(),
isRestOrSpread: isRestOrSpread,
decorators: decorators
};
} else {
return {
parameter: paramName,
defaultValue: null,
isRestOrSpread: isRestOrSpread,
decorators: decorators
};
}
}
/*
const params = getFunctionParameters(function test(
a,
b = 5,
...c
) { console.log(a, b, c); })
console.log(params.map(analyzeParameter));
---
const exampleFunc = 'function(@defaultValue(["a"]) a, @defaultValue(5, false) b, ...rest) {};';
const params = getFunctionParametersFromString(exampleFunc).map(analyzeParameter)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment