JavaScript — write a function that can solve a math [removed]without eval)

后端 未结 2 1059
礼貌的吻别
礼貌的吻别 2020-12-21 06:45

Ultimately I want to take this:

2x + 3 = 5

and solve for x, by first subtract 3 from both sides so 2x = 2, then divide both si

2条回答
  •  感情败类
    2020-12-21 07:32

    You can do that in following steps:

    • First of all use split() and split by the + and - which will occur after multiplication and division.
    • Then use map() on array and split() it again by * and /.
    • Now we have a function which will which will evaluate an array of numbers with operators to single number.
    • Pass the nested array to complete multiplication and division.
    • Then pass that result again to sovleSingle and perform addition and subtraction.

    The function works same as eval as long as there are no brackets ().

    Note: This doesnot matters the which occurs first among + and - or which occurs first among * and /. But *,/ should occur before +,-

    function solveSingle(arr){
      arr = arr.slice();
      while(arr.length-1){
        if(arr[1] === '*') arr[0] = arr[0] * arr[2]
        if(arr[1] === '-') arr[0] = arr[0] - arr[2]
        if(arr[1] === '+') arr[0] = +arr[0] + (+arr[2])
        if(arr[1] === '/') arr[0] = arr[0] / arr[2]
        arr.splice(1,1);
        arr.splice(1,1);
      }
      return arr[0];
    }
    
    function solve(eq) {
      let res = eq.split(/(\+|-)/g).map(x => x.trim().split(/(\*|\/)/g).map(a => a.trim()));
      res = res.map(x => solveSingle(x)); //evaluating nested * and  / operations.
       
      return solveSingle(res) //at last evaluating + and -
      
      
    }
    
    console.log(solve("3 - 6 * 3 / 9 + 5")); //6
    console.log(eval("3 - 6 * 3 / 9 + 5")) //6

提交回复
热议问题