Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

411
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!