In js: how to get an object that includes all function arguments, including default parameters?

I recently learned about the ES6 function, which allows you to define the parameters of a function with a deconstructing object. In this way

function makeGenerator({type, max}) {
  //some code
  return something
}

I really liked this approach because it allowed me to see the arguments needed for the function, where it is defined and where it is called. (Really good for self-documenting code!)

I used it along with the default arguments:

function makeGenerator({type = "natural", max = 10})

This works great!

But...

Sometimes I would like, as a rule, for debugging purposes (but not limited to this) to get a summary of all the function arguments. However:

function makeGenerator({type = "natural", max = 10}) {
  console.log(arguments[0])
}

makeGenerator({type = "fibanacchi"});

will output:

{type: "fibanacchi"}

, max, , 10, , .

, - :

{type: "fibanacchi", max: 10}

, , .

?

+4
2

.

function getArguments(fn) {
    var string = fn.toString(),
        count = 0,
        start = string.indexOf('('),
        i = start;

    while (i < string.length) {
        if (string[i] === '(') {
            count++;
        } else if (string[i] === ')' && !--count) {
            return string.slice(start + 1, i);
        }
        i++;
    }
    return '';
}

function makeGenerator({ type = "natural", max = 10 }) {
    console.log(arguments[0])
}

function fn({ fo = 42, bar = (1 + (3)) * 4 }) { }

console.log(getArguments(makeGenerator));
console.log(getArguments(fn));
Hide result
+2

max, . , , , .

max, , .

+2

Source: https://habr.com/ru/post/1691704/


All Articles