Use of Eval. Is there any alternative in this case?

Asked

Viewed 75 times

0

I came across the functionalities of eval() and I started using, but I learned about the risk in using eval() next to a input external.

I use the eval() to receive from a input-text to string which corresponds to a polynomial function. It was the most practical short-term alternative that I managed to pass a user data as variables and mathematical operations.

Are there risks in hosting a code with this function in the future? Is there an alternative to the eval() in that capacity?

function inserirLinhaTabela() 
{

    //Cálculo numérico: 

    var poli = document.getElementById("fx").value;
    var troca = 
    {
        sen: "Math.sin",
        cos: "Math.cos",
        e: "Math.E",
        ln: "Math.log",  
    }

    poli = poli.replace(/sen|cos|e|ln/gi, function(matched){
      return troca[matched];
    });

    function fdex(x)
    {
        return eval(poli);
    }
  • 2

    It is a good initiative to ask how to avoid an Eval, but the essential has already been said in the comments of your previous question. The answer given here is an excellent starting point for implementing the suggested parser. The following research can be used as a starting point: https://www.google.com/search?q=javascript+polynomial+parser

1 answer

3


If I understood anything at all:

var funcoes = {
    sen: Math.sin,
    cos: Math.cos,
    e: Math.E,
    ln: Math.log,  
}
var funcao = "sen";
console.log(funcoes[funcao](30));

I put in the Github for future reference.

Instead of using texts I took the same functions and just called them without needing the eval(). A rough summary of eval() is to remove the quotation marks from a text and execute what was inside, so why not remove the quotation marks in your code?

I think it answers the rest of the question: Eval is either good or bad?.

Note that to catch general expressions you will have to make one parser the same way, and then you can use a slightly different form of this, the answer was on top of the presented code and not the whole context that later I saw that already existed in another question of the AP.

  • So. This "swap" variable is only for the user not to have to type Math.sin() when performing the operation. Making it friendlier for those who don’t know JS and the Math library.

  • 2

    Sm, this is in the question. Is there any part that did not understand the answer, or that you think needs to be explained better?

  • The Eval is being used to receive the function as a whole in that specific part: Function inserLinhaTable() { //Numerical calculus: var poli = Document.getElementById("fx"). value; Function fdex(x) { Return Eval(poli); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.