1
votes

I am building simple calculator with Vue, and I don't know how to transform string into math operation. I already have string building code.

<template>
  <div>
    <input type="number" placeholder="number" v-model="number">
    <button @click = "addToOperation('+')">+</button>
    <button @click = "addToOperation('-')">-</button>
    <button @click = "addToOperation('*')">*</button>
    <button @click = "addToOperation('/')">/</button>
  </div>
</template>

<script>

export default {
    data(){
      return{
        number: '',
        operation: ''
      }
    },
    methods:{
        addToOperation(sign){
          this.operation += this.number + sign 
        }
    }
}

</script>

Thank you in advance :).

2
There are many ways it could be done; a simplistic expression parser is a fun exercise. There are also libraries that'll do it for you (e.g., mathjs).Dave Newton

2 Answers

0
votes


There are three ways I know to achieve this:

The first and worst way:

var result;
eval("result = calculation");

Please don't use this, because eval is evil. It evaluates Strings into codes and creates vulnerability against your site security. The only way I'd use it is when it's a personal site where no one has access.

The second option:

Create a function that splits the String by operators and then performs the mathematical actions. I'd do this if the calculator won't be too complicated in the end.

The third option:

Don't add the operator - Add a mathematical action to a kind of query. And when you want to calculate this. just go through the query. Pay attention to the mathematical order!

That were the 3 ways that occurred to me at the moment and I hope I could help
ShadowLp174

0
votes

I would advice you make separate methods for each operation instead. It produces cleaner to understand code and you will not have so much extra code anyways:

<button @click = "add()">+</button>
<button @click = "subtract()">-</button>
<button @click = "multiply()">*</button>
<button @click = "divide()">/</button>