Home>

How to make such a story for a calculator using only JavaScript?

what does history mean?

Grundy2021-11-20 06:39:45

@Grundy magazine like in Windows 10 calculator

aquaprogit2021-11-20 06:39:45

@Grundy "Once upon a time there was a calculator ..."

Igor2021-11-20 06:39:45

@SeeSharp what kind of magazine?

Grundy2021-11-20 06:39:45

Fourteen comments about nothing)) Well, first, your user enters the desired expression and you calculate the result. Therefore, you already have all the data somewhere at hand, if the calculator is written: expression + result. Just store /display them in a convenient form and do not lose by saving ... yes, at least in an array. And in the sequel, decide how you will save them further. you have enough options and their lifetime is different: during the session, in cookies, in localStorage, send to the server, .

Alex Krass2021-11-20 06:39:45
  • Answer # 1

    Just shove into an array of objects. If in c++, then create a class with the required fields and then create an array of objects of this class.

    var exprs= [
      {
        "value1": 7,
        "symbol": "+",
        "value2": 9
      }
    ]
    function evalute (exprobj)
    {
      if (exprobj.symbol== "+")
      {
        return exprobj.value1 + exprobj.value2;
      }
    }
    function getExpr (exprobj)
    {
        return exprobj.value1 + "" + exprobj.symbol + "" + exprobj.value2;
    }
    console.log (getExpr (exprs [0]));
    console.log ("=");
    console.log (evalute (exprs [0])); 
  • Answer # 2

    Just shove into an array of objects. If in c++, then create a class with the required fields and then create an array of objects of this class.

    var exprs= [
      {
        "value1": 7,
        "symbol": "+",
        "value2": 9
      }
    ]
    function evalute (exprobj)
    {
      if (exprobj.symbol== "+")
      {
        return exprobj.value1 + exprobj.value2;
      }
    }
    function getExpr (exprobj)
    {
        return exprobj.value1 + "" + exprobj.symbol + "" + exprobj.value2;
    }
    console.log (getExpr (exprs [0]));
    console.log ("=");
    console.log (evalute (exprs [0])); 
  • Answer # 3

    Personally, I was extremely attracted to storing such information by JSON strings and files. It was convenient for me to use them both on the web and on Android. Let a new object be added to the JSON array for each new calculation, in which the used numbers and operators over them will be sequentially stored, for example, like this:

    {
      "number_1": 2,
      "operator_1": "+",
      "number_2": 2,
      "result": 4
    } 

    When you need to use history, the program will simply sequentially display such blocks stored in a file. One has only to write a working interpreter who understands this correctly. I will leave a brief information on working with JSON here