Using Function
is an anti-pattern. It's one degree away from eval
and there's always a better way to write things, especially considering JavaScript already supports first-class functions -
const add = (a, b) => a + b
const multiply = (a, b) => a * b
console.log("your sum is: " + add(3,7))
console.log("your product is: " + multiply(3,7))
your sum is: 10
your product is: 21
If instead you want to access functions using "+"
and "*"
strings, you can create a simple lookup and throw an Error when a particular operation is not supported -
const operations = {
"+": (a, b) => a + b,
"*": (a, b) => a * b
}
function simpleOperations(op) {
const f = operations[op]
if (f == null)
throw Error(`unsupported operation: ${op}`)
return f
}
const add = simpleOperations("+")
const multiply = simpleOperations("*")
console.log("your sum is: " + add(3,7))
console.log("your product is: " + multiply(3,7))
const divide = simpleOperations("/") // <- not yet implemented
your sum is: 10
your product is: 21
Error: unsupported operation: /
Implementing a simple calculator is a great way to learn how to write your first programming language. If this sort of thing interests you, see this related Q&A.