4

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?

5 Answers 5

6

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));

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You could rewrite it a little and then use map:

function thing(a, b) {
  return Math.pow(a * b, 2);
}
var commandQueue = [
  function() {
    return thing(100, 0);
  },
  function() {
    return thing(100, 233) % 6;
  },
  function() {
    return thing(100, 422) % 6;
  }
];
var commandResults = commandQueue.map(function(a) {
  return a();
});
console.log(commandResults);

Comments

1

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


function getThingSecondArg(fn) {
    return +/thing\([^,]*,([^,]*)/.exec(fn)[1].trim();
};

function sum(arr) {
    for (var i=0, result=0; i<arr.length; i++) {
        result += arr[i];
    }
    return result;
}

console.log(sum(commandQueue.map(getThingSecondArg)));

Comments

0

You can do it like this:

const sum = commandQueue.reduce((acc, val) =>
  Number(val.toString().split(',')[1]) + acc, 0);
console.log(sum);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.