0

I wanted to replace desig values in my string formula to evaluate the expression.

I have an array such as:

var value_array = [
  {value: "1", desig: "ABM"},
  {value: "2", desig: "LF"},
  {value: "3", desig: "DM"},
  {value: "4", desig: "CM"},
  {value: "5", desig: "AN"}
];

And the formula is:

(ABM+ABM)* LF*(DM*LF)+CM+AN *AN/LF                   

I should get:

(1+1)* 2*(3*2)+4+5 *5/2

then I will evaluate the string which resulted from 40,5.

Thanks for your help.

Rick
  • 4,030
  • 9
  • 24
  • 35
alperzzz
  • 53
  • 5

3 Answers3

3

You can try this

var value_array = 
[{value: "1", desig: "ABM"},
{value: "2", desig: "LF"},
{value: "3", desig: "DM"},
{value: "4", desig: "CM"},
{value: "5", desig: "AN"}];

let formula =  '(ABM+ABM)* LF*(DM*LF)+CM+AN *AN/LF'

value_array.forEach( item => {
    formula = formula.replace(new RegExp(item.desig,'g'), item.value )
})
console.log( eval( formula ))
GansPotter
  • 761
  • 5
  • 8
1

Instead of using an array you should use a Dictionnary, and then access the row you want like that :

var values = {
   "ABM": 1,
    "LF": 2
};

and then in your formula use it like that :

var res = (values["ABM"] * values["LF"]);
Lucas Tambarin
  • 395
  • 3
  • 14
0

Used positive lookahead to match only desig word without groups and not match, for example, token ABM with ABMS or something:

var regexTemplate = "(?<=[^A-Z]|\s)$token(?=[^A-Z]|\s|$)";

var value_array = 
[{value: "1", desig: "ABM"},
{value: "2", desig: "LF"},
{value: "3", desig: "DM"},
{value: "4", desig: "CM"},
{value: "5", desig: "AN"}];

var formula = '(ABM+ABM)* LF*(DM*LF)+CM+AN *AN/LF';

var expr = value_array.reduce(function(acc, v){
   var regex = new RegExp(regexTemplate.replace('$token', v.desig), "g");
   acc = acc.replace(regex, v.value);
   return acc;
}, formula);

console.log(eval(expr));
Max Sinev
  • 5,884
  • 2
  • 25
  • 35