1

I want to know if it possible to get the names (not the values) of the function parameters from outside of a function, either with a native JavaScript function/method or something custom.

// function parameters cat, dog, bird
function foo(cat, dog, bird) {};

// now access these names from outside the function, something like (pseudocode)
foo.getFunctionParameters(); 

or

getFunctionParameters(foo);

Which would log

['cat', 'dog', 'bird']

The reason: I have an object that has a values functions. These functions have different function parameters. I must loop through this Object and execute the function. I do not want to pass a key with each Object that contains the function, telling me which function parameter to pass (via an if...else). I'd simply create an Object with my possible function parameters and the use the actual function parameters to access the needed values.

const someArray = [
    {
        foo: [
            {
                function: (cat, dog) => {...},
                otherKeys: otherValues,
            },
            {
                function: (apple, orange) => {...},
                otherKeys: otherValues,
            },
            {
                function: (cat, apple) => {...},
                otherKeys: otherValues,
            },
            ...
        ],
        ...
    }
]

Then I'd simply construct an object with the possible function parameters

const possibleFuncParams = {
    cat: 'Sweet',
    dog: 'More a cat person',
    apple: 'I like',
    orange: 'not so much',
    ...
}

And then use the function paramaters coming back from getFunctionParameters() to access the object (something like this):

const keys = getFunctionParameters();
possibleFuncParams[keys[0]];
possibleFuncParams[keys[1]];

What I do not want to do is

const someArray = [
    {
        foo: [
            {
                function: (cat, dog) => {...},
                otherKeys: otherValues,
                keyToSelectFuncParam: 'animals'
            },
            {
                function: (apple, orange) => {...},
                otherKeys: otherValues,
                keyToSelectFuncParam: 'fruits'
            },
            {
                function: (cat, dog) => {...},
                otherKeys: otherValues,
                keyToSelectFuncParam: 'mixed'
            },
            ...
        ],
        ...
    }
]

And then

if(keyToSelectFuncParam === 'animals') {
    foo.functio('Sweet', 'More a cat person');
}
four-eyes
  • 10,740
  • 29
  • 111
  • 220

1 Answers1

0

I got this by googling... try it

// JavaScript program to get the function
// name/values dynamically
function getParams(func) {

  // String representaation of the function code
  var str = func.toString();

  // Remove comments of the form /* ... */
  // Removing comments of the form //
  // Remove body of the function { ... }
  // removing '=>' if func is arrow function
  str = str.replace(/\/\*[\s\S]*?\*\//g, '')
    .replace(/\/\/(.)*/g, '')
    .replace(/{[\s\S]*}/, '')
    .replace(/=>/g, '')
    .trim();

  // Start parameter names after first '('
  var start = str.indexOf("(") + 1;

  // End parameter names is just before last ')'
  var end = str.length - 1;

  var result = str.substring(start, end).split(", ");

  var params = [];

  result.forEach(element => {

    // Removing any default value
    element = element.replace(/=[\s\S]*/g, '').trim();

    if (element.length > 0)
      params.push(element);
  });

  return params;
}

// Test sample functions
var fun1 = function(a) {};

function fun2(a = 5 * 6 / 3, // Comment
  b) {};

var fun3 = (a,
  /*
   */
  b, //comment
  c) => /** */ {};

console.log(`List of parameters of ${fun1.name}:`, getParams(fun1));
console.log(`List of parameters of ${fun2.name}:`, getParams(fun2));
console.log(`List of parameters of ${fun3.name}:`, getParams(fun3));
Ingenious_Hans
  • 724
  • 5
  • 16