Reputation: 171
I have created getResult function to perform calculation according to formula. is there any way to perform this calculations please let me know if you have any solution.
Thanks in Advance
let formula = "a*b";
let parameters = {a:3,b:4}
let getResult = function(formula, parameters){
}
Upvotes: 0
Views: 41
Reputation: 63550
A simple calculator that doesn't rely on eval
:
let formula = "a*b";
let parameters = {a:3,b:4}
function getResult(formula, parameters){
const operator = formula.match(/[+-\/*]{1}/)[0];
const {a, b} = parameters;
switch(operator) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
}
const result = getResult(formula, parameters);
console.log(result);
Upvotes: 1
Reputation: 4184
Try this. Though "eval" is something to be avoided.
let formula = "a*b";
let parameters = {a:3,b:4}
let getResult = function(formula, parameters){
let cal = [...formula].map(d => parameters[d] || d).join('')
return eval(cal)
}
console.log(getResult(formula, parameters))
Upvotes: 0