Is there a substitute for using eval() in this situation?

Looking for input on creating a calculation function for my Dialogflow app without using eval() since it can be harmful. Are there any alternative methods for this purpose?

For example:

var number = 4
var number1 = 9
var operator = '+'

console.log(eval(number + operator + number1));

This is what I have so far:

function Calculation(agent){

  var number = request.body.queryResult.outputContexts[0].parameters.number;
  var number1 = request.body.queryResult.outputContexts[0].parameters.number1;
  var operator = request.body.queryResult.outputContexts[0].parameters.calculation;

  var result = (eval(number + operator + number1));

  agent.add(result);

}

Answer №1

If you have specific limitations to work with, you could create a structure that connects mathematical operators to their corresponding functions.

var operations = {
  '+': (a,b) => a+b,
  '-': (a,b) => a-b,
  '*': (a,b) => a*b,
  '/': (a,b) => a/b
}

var number1 = 4;
var number2 = 9;
var operator = '+';
var operation = operations[operator];

console.log( operation(number1,number2) );

Answer №2

If you're looking for another solution, consider checking out the mathjs package. With this package, you can utilize the math.eval() function just like how you would use eval() in your code snippet above.

let number = 4;
let number1 = 9;
let operator = '+';

console.log(math.eval(number + operator + number1)); // Output: 13
console.log(typeof math.eval(number + operator + number1)); // Output: "number"

An important thing to note is that downloading the entire package may be a drawback, as it amounts to 136 kB when minified and gzipped. Another alternative is to explore their public API for similar functionality, but this has its own set of advantages and disadvantages to consider.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Establish map boundaries using the longitude and latitude of multiple markers

Utilizing Vue, I have integrated the vue-mapbox component from this location: I've made sure to update the js and css to the latest versions and added them to the index.html: <!-- Mapbox GL CSS --> <link href="https://api.tiles.mapbox.com/m ...

Having trouble adding flexslider before a div element with jQuery

Hey there! I recently got flexslider from woothemes.com. The page structure I'm working with looks something like this: <div class="parentdiv anotherdiv"> <div class="child-div1">some buttons here</div> <div class="child-div2"& ...

Leveraging server-side HTML templates with ReactJS

I'm having difficulty with Reactjs and rendering components. Essentially, I have standard html templates on the server and I'm attempting to utilize them as JSX components within React. Everything seems to be working fine, except I am unable to ...

If the URL matches a specific path, then append a parameter

I've created a script that adds a parameter to a URL based on specific subfolders. For example, if the URL contains /de, it will add ?_sft_language=german. However, I'm encountering an issue where the code is running multiple times instead of jus ...

Maximizing the benefits of the express.js API through functions such as fetching data with get, sending

As someone who is just starting out in web development, I have recently delved into node and express 4.9.0. After going through some tutorials and experimenting with the API, it's clear to me that the http protocol and request URLs are essential comp ...

Using AngularJS to add a unique custom class directive to each item in an ng-repeat loop

Can anyone help me figure out why the width of a div isn't being set dynamically using AngularJS? <ul id="contents"> <li ng-repeat="content in contents"> <div class="content_right custom_width"> <div class="title"> ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Tips for adjusting the button color in Material UI by utilizing the ":active" pseudo-class

In the project I am currently working on, I am incorporating Material UI. One of the tasks I need to complete is changing the active state of a button. I have implemented both hover and active states from Material UI in my code: const useStyles = makeStyle ...

Developing a feature that eliminates an array and appends its contents to a list

I'm currently engaged in learning Javascript through freecodecamp and am diving into the topic of functions. Currently, I'm tackling a problem where I need to create a type of queue that can remove the first item from an array and replace it wit ...

The functionality of the mathjs eval function varies when used with and without a string input

When I calculate Arithmetic operations using the math.eval function without quotes, null values are ignored and correct results are obtained. However, if I use quotes in the same function, it throws an error. The issue is that I require strings because I ...

Guide on redirecting the user to the "notFound" page within the getServerSideProps function in Next.JS whenever an incorrect params.id is provided

export const getServerSideProps = async ({ params }) => { const res = await fetch( `https://pixabay.com/api/?key=${process.env.API_KEY}&id=${params.id}` ); const { hits } = await res.json(); if (!hits) { return { notFound: tr ...

Dealing with Three.JS, Amazon S3, and the challenges of access control origin errors in hosting JavaScript files

Overview In order to showcase models stored on Amazon S3, we rely on the use of the Three.JS Javascript library for visualization. For loading models, I exclusively utilize the JSONLoader due to its comprehensive toolchain support. Other formats such as ...

Error encountered in $element when utilizing $mdDialog in AngularJS Material

Attempting to resolve an error appearing in the console, which only occurs on the server and not locally. The specific error can be viewed by clicking this link: https://errors.angularjs.org/1.5.8/$injector/unpr?p0=%24elementProvider%20%3C-%20%24element%2 ...

Using the $.each method instead of a traditional for loop

validateScaledIntegerNumberGridFields: function(frm) { var fields = $('.scaledInteger', frm); var result = true; $.each(fields, function(index) { var scale = $(this).data("scale"); ...

Sending an Array from a ReactJS Frontend to a Django Backend using JavaScript and Python

I successfully created a website using Django and React JS. In my project, I am working on passing an array named pict from the frontend JavaScript to the backend Python in Django. let pict = []; pictureEl.addEventListener(`click`, function () { console ...

Looping through an array of images using JavaScript

Currently, I have a computer science test at school, and the main question is to create a traffic light that changes colors in a loop using arrays. I am facing some challenges with this question, but I believe I am close to solving it. Below is my code sni ...

Tips for extracting innerHTML or sub-string from all elements that have a specific class name using JavaScript

When it comes to shortening the innerHTML of an element by its Id, I have found success using either slice or substring. While I'm not entirely clear on the differences between the two methods, both accomplish what I need them to do. The code snippet ...

Why does my loading screen appear again when I submit the form and refresh the page?

I've been working on setting up a login page and was able to create a loading screen that fades away once the page has finished loading. $(window).on("load",function(){ setTimeout(function() { $(".lo ...