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?
CodePudding user response:
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);
CodePudding user response:
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.