Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query the arguments of a javascript function without calling it

Given a command queue looking something like the following . .

var commandQueue = [
        function() {thing(100, 0, shiftFunc)},
        function() {thing(100, 233, shiftFunc)},
        function() {thing(100, 422, shiftFunc)}
];

How can I write a function that takes the commandQueue as a parameter and returns the sum of the second arguments (index [1]) to the functions in the queue without calling the functions in the queue?

like image 400
learnvst Avatar asked Jan 05 '23 11:01

learnvst


2 Answers

You could use Function#toString and a regular expression, which search for the value between the first and second comma.

var commandQueue = [
        function() {thing(100, 0, shiftFunc)},
        function() {thing(100, 233, shiftFunc)},
        function() {thing(100, 422, shiftFunc)}
];

console.log(commandQueue.reduce(function (r, a) {
     return r + +((a.toString().match(/,\s*(\d+),/) || [])[1] || 0);
}, 0));
like image 124
Nina Scholz Avatar answered Jan 07 '23 11:01

Nina Scholz


This isn't possible, unfortunately. JavaScript provides no ability to peek inside a function definition.

like image 44
Mike Lawson Avatar answered Jan 07 '23 10:01

Mike Lawson