0

please someone help me about my javascript code. I want to convert string to be computable. Example: var string = "34.5 + 30";

the javascript function or code will automatically compute my string value. So the result will be 64.5 with a float or decimal data type.

hope someone can answer my query.

  • Will there only be addition `+` operation here? Is it possible, there will be `*`, `-`, or `/` operations also. – DecPK Oct 06 '21 at 04:37
  • 2
    This exercise is designed to teach you how to write your own programming language. In string form `34.5 + 30` is just a sequence of bytes. If we `tokenize` it, we can break it into meaningful tokens, `34.5`, `"+"`, and `30`. If we `parse` it, we can build a syntax tree like `{ operation: "+", arguments: [34.5, 30] }`. Writing our own `evaluate`, we can compute the final result, `74.5`. I think you will find [this Q&A](https://stackoverflow.com/a/69168750/633183) to be extremely helpful. – Mulan Oct 06 '21 at 04:46
  • Please provide enough code so others can better understand or reproduce the problem. – Community Oct 10 '21 at 16:59

1 Answers1

1

Use eval function.

Reference

The eval() function evaluates JavaScript code represented as a string.

But there is a security issue in this.

Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). See Never use eval()!, below.

var myString = "34.5 + 30";
console.log(eval(myString));

Since eval has some security issues, its always adviced not to use it. You could either make use of some custom libraries or implement your own parsing logic.

Please find a small paring logic from my side.

Please note, this evaluates the mathematical expressions linearly. This doesnot works with BODMAS rule or will not evaluate any complex expression. This is to evaluate a mathematical expression that contains only numbers, and basic operators such as +, -, * and /. If you wish to have custom validations you could build on top of this or can implement a solution of your own.

I have added the description as code comment

const myString = "34.5 + 30";

// Regex to split the expression on +, -, *, / and spaces
const isNumeric = /(?=[-+*\/(\s+)])/;

// Valid operators
const operators = ['+', '-', '*', '/'];

// Split the string into array
const expressionArray = myString.split(isNumeric);

// Object to hold the result and the operator while parsing the array generated
const result = { result: 0, operator: '' };

// loop though each node in the array
// If an operator is found, set it to result.operator
// If not an operator, it will be a number
// Check an operator is already existing in result.operator
// If then perform the operation with the current node and result and clear the result.operator
expressionArray.forEach((node) => {
  const trimmedNode = node.trim();
  if (trimmedNode) {
    if (operators.indexOf(trimmedNode) === -1) {
      if (result.operator) {
        switch (result.operator) {
          case '+':
            result.result += Number(node);
            break;
          case '-':
            result.result -= Number(node);
            break;
          case '*':
            result.result *= Number(node);
            break;
          case '/':
            result.result /= Number(node);
            break;
            result.operator = '';
        }
      } else {
        result.result += Number(node);
      }
    } else {
      result.operator = trimmedNode;
    }
  }
});
console.log(result.result);
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • @HevinSiatonEbarle What all operators do you have? Is it just `+` or other operators? – Nitheesh Oct 06 '21 at 04:45
  • 1
    @HevinSiatonEbarle See [_"Never use eval!"_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#never_use_eval!) on the MDN wiki – Mulan Oct 06 '21 at 04:47
  • @HevinSiatonEbarle please approve the answer, if this is what you are looking for. – Nitheesh Oct 06 '21 at 06:25