javascriptmathjs

Get distinct products of a sum-of-products expression mathjs/js


Is there a way using Mathjs or some other js lib or even plainjs to get the distinct products of a sum-of-products expression? F.e given this expression as a string:

7.30*7.40-2.10*1.30+8.10*(2.70+0.60+4.70)+0.30*0.60+ 1.60*0.70+2.95*2.65+6.00*5.80

The function should execute only the multiplications and return the distinct sums of the different products.

the result should be: 54.02 - 2.73 + 64.8 + 0.18...

it should respect parenteses.


Solution

  • let str = "7.30*7.40-2.10*1.30+8.10*(2.70+0.60+4.70)+0.30*0.60+ 1.60*0.70+2.95*2.65+6.00*5.80"
    
    let strArr = str.split("*")
    
    let parsedParenthesis = strArr.map(expression => {
      if (!isNaN(expression))
        return expression
      let regex = /\(([^()]+)\)/g
      if (regex.test(expression)) {
        let matched = (expression.match(regex))[0]
        let exp = matched.split(/[\(\)]/)[1]
        let evaluatedExp = math.evaluate(exp) //if using mathjs
        expression = expression.replace(matched, evaluatedExp)
      }
      return expression
    })
    let finalString = parsedParenthesis.join("*")
    let multiplyArr = finalString.match(/(\d+\.?\d*\*\d+\.?\d*)/g)
    multiplyArr.map(exp => {
      let evaluatedExp = Math.round((math.evaluate(exp) + Number.EPSILON) * 100) / 100 //if using mathjs
      finalString = finalString.replace(exp, evaluatedExp)
    })
    console.log(finalString)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/7.0.2/math.js"></script>