• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

151
Vistas
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?

almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

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);
almost 3 years ago · Juan Pablo Isaza Denunciar

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.

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda