1

This my code:

const addition = (num1, num2) => num1 + num2;

const subtraction = (num1, num2) => num1 - num2;

const multiplication = (num1, num2) => num1 * num2;

const division = (num1, num2) => num1 / num2;

const command = {
  add: addition,
  subtract: subtraction,
  multiply: multiplication,
  division,
  execute: function(action, { num1, num2 }) {
    return this[action](num1, num2);
  }
};

const calculate = (action, numbers) => {
  const result = command.execute(action, numbers);
  console.log(
    `In ${action} of numbers ${Object.values(numbers)} the result is ${result}`
  );
};

calculate('add', { num1: 2, num2: 3 });

It is the command pattern that I did but I think if it could be the command like this or something that you declare operator to execute after to depend of action:

const command = {
  add: '+',
  subtract: '-',
  multiply: '*',
  division: '/',
  execute: function(action, { num1, num2 }) {
    return num1 this[action] numb2;
  }
};

My question if this would be possible or the first code is good?

Because I see all the function in command is very similar the only change of the functions is the operator

  • Welcome to StackOverflow; please review the question title. Have also a look at [writing the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question). – Jeroen Heier Sep 25 '19 at 18:59
  • can you add an example of the use case and the wanted result? – Nina Scholz Sep 25 '19 at 18:59

1 Answers1

1

if this would be possible or the first code is good?

It is possible and the first code is good

For the second code block to be possible you'll need eval, which is to be avoided and not recommended:

const command = {
  add: '+',
  subtract: '-',
  multiply: '*',
  division: '/',
  execute: function(action, { num1, num2 }) {
    return eval(`${num1} ${this[action]} ${num2}`);
  }
};

console.log( command.execute('add', {num1: 5, num2: 6}) );
Taki
  • 17,320
  • 4
  • 26
  • 47