Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

412
Visualizações
Define a factory function that accepts a set of operators as inputs

I have been working on a simple calculator app using client side javascript and have implemented the program logic for the basic mathematical operations +, -, x, /. The code is implemented as callback functions so they can be used in event handlers.

   add = (a , b) => a + b
   subtract = (a , b) => a - b
   multiply = (a, b) => a * b
   divide = (a, b) => a / b

I have read that factory functions are useful in situations such as this where the structure of each function is similar. However I'm not sure how you can create factory functions the set to be mapped are operators. Something like, createOperation("add") would return (a , b) => a + b, createOperation("subtract") would return (a, b) => a - b etc.

My first thought was to convert everything to a string, concatenate them and then return using eval. Something like eval("(example) => example.output"). From what I've read in the MDN docs and elsewhere this is highly discouraged.

Is there a way to achieve this without resorting to the eval hack?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

function createOperation(operator, { a, b }) {
  switch (operator) {
    case "add":
      return a + b;
    case "substract":
      return a - b;

    // .... implement for mul and div operator

    default:
      throw new Error("please provide correct operator");
  }
}

const result = createOperation("substract", { a: 3, b: 5 });
console.log(result);
about 4 years ago · Juan Pablo Isaza Relatório

0

Using mapping and a factory function can look like this. You can also use an enum to hold action names :)

const mapping = {
  mul: (a, b) => a * b,
  add: (a, b) => a + b
};

const factory = (action) => {
  if (mapping.hasOwnProperty(action)) {
    return mapping[action];
  }
  throw new Error("Action does not exist");
};

const add = factory("add");
console.log(add(1, 2));

In this example, we have mapping variable, which maps action key to the respective function. factory function retrieves each action from this mapping variable and returns it. No key found - usually should not be allowed, so an Error is thrown.

You can use Map, instead of an object, especially useful if keys can be other than string type.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda