You could use the Function
constructor, but your shouldn't, as it will attempt to run any arbitrary code contained within the string. A safer choice would be to use a switch
statement and whitelist the supported operations -
function applyOperator(op, a, b)
{ switch (op)
{ case "+": return a + b
case "-": return a - b
case "*": return a * b
case "/": return a / b
case "%": return a % b
case "^": return Math.pow(a, b)
default: throw Error(`unsupported operator: ${op}`)
}
}
console.log(applyOperator("*", 3, 5))
console.log(applyOperator("-", 3, 5))
console.log(applyOperator("+", 3, 5))
console.log(applyOperator("!", 3, 5))
15
-2
8
Error: unsupported operator: !
Another safe option is to define a set of supportedOperations
. When calling applyOperation
, check if the op
is supported and call it, otherwise throw an error -
const supportedOperations =
{ "+": (a, b) => a + b
, "-": (a, b) => a - b
, "*": (a, b) => a * b
, "/": (a, b) => a / b
, "%": (a, b) => a % b
, "^": (a, b) => Math.pow(a, b)
}
function applyOperator(op, a, b)
{ if (op in supportedOperations)
return supportedOperations[op](a, b)
else
throw Error(`unsupported operator: ${op}`)
}
console.log(applyOperator("*", 3, 5))
console.log(applyOperator("-", 3, 5))
console.log(applyOperator("+", 3, 5))
console.log(applyOperator("!", 3, 5))
15
-2
8
Error: unsupported operator: !