Billedale
Billedale

Reputation: 51

Changing the function that is called within a function in javascript

I have different functions that run very simple mathematical equations. I want to have a function that is able to call any of these functions based on a variable that is set separately. I can't seem to get the function to recognize the variable as a "function" input.

When run in console, this gives me the result I'd expect:

function operate(whatOp, a, b){
  console.log(whatOp(a, b)}

So typing...

operate(divide, 3, 4)

...in console returns 0.75.

Yet, if I try to call it by having whatOp come from a variable, it doesn't work as...

let firstNumber = "999";
let secondNumber = "333";
let operation = "divide";;
operate(operation, firstNumber, secondNumber)

...in console returns undefined.

How do I get it to work based on this? I'm using a button to set the variable, but that's working and returns the value I want, so I think it has to do with the way I'm calling the variable?

Upvotes: 0

Views: 63

Answers (4)

EddiGordo
EddiGordo

Reputation: 686

You should check if the operation you need to execute is present in the global space. What i use to do is :

if (window[operation])
{
    operate(window[operation], firstNumber, secondNumber);
}
else
{
    console.error("Operation", operation, "not yet implemented !");
}

Hope it helps.

Upvotes: 1

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10384

Some day, programming languages will be so intelligent that you will just say "divide" and they will divide two numbers. That day isn't arrived yet, so you have to specify what "divide" means. You can do it by defining a function:

function operate(whatOp, a, b){
  console.log(whatOp(a, b));
}

let firstNumber = "999";
let secondNumber = "333";
let operation = function divide(firstArgument, secondArgument) {
    return firstArgument / secondArgument; // Here is where you specify what "divide" is
}

operate(operation, firstNumber, secondNumber);

Upvotes: 0

Dez
Dez

Reputation: 5838

You can do something like:

function add(a, b) {
  return a + b;
}

function rest(a, b) {
  return a - b;
}

function divide(a, b) {
  return a / b;
}

function operate(whatOp, a, b){
  const operations = {
    add,
    rest,
    divide
  };

  return operations[whatOp](a, b);
}

function add(a, b) {
  return a + b;
}

function rest(a, b) {
  return a - b;
}

function divide(a, b) {
  return a / b;
}

function operate(whatOp, a, b){
  const operations = {
    add,
    rest,
    divide
  };

  return operations[whatOp](a, b);
}

console.log(operate('add', 1, 2));
console.log(operate('rest', 2, 1));
console.log(operate('divide', 4, 2));

Upvotes: 1

ChechoCZ
ChechoCZ

Reputation: 312

I had to do something similar, and I could do it by writing a simple switch statement:

function yourFunction(operation, a, b) {
  switch (operation) {
    case 'sum':
      sum(a, b);
      break;
  }
}

Hope it helps...

Upvotes: 0

Related Questions