Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls.

I'm aware that using `eval` is deemed unsafe and not the most ideal method. However, at present, I'm struggling to come up with an alternative solution that aligns with my requirements.

Is there a more secure or effective way to achieve the same functionality?

vm.saveRecord = function() {
    var service = '';

    if(vm.valueTrue) {
        service = vm.otherValue ? 'function1' : 'function2';
    } else {
        service = vm.otherValue ? 'function3' : 'function4';
    }

    eval(service).callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                // Handle successful response
            }
        }, function errorCallback(response) {
            // Handle error
        }
    )
};

Answer №1

Utilizing a function handle is key when it comes to executing functions efficiently. The function handle serves as a reference to the specific function that needs to be executed:

//pre-existing functions
function first() {   console.log("first")   };
function second() {   console.log("second")   };
function third() { console.log("third") };

//function responsible for executing other functions
function execute(num) {
  //declaring a variable to store the chosen function
  let toRun;
  
  //determining which function to execute based on input number
  if (num == 1) {
    toRun = first;
  } else if (num == 2) {
    toRun = second;
  } else if (num == 3) {
    toRun = third;
  }
  
  //calling the assigned function by using ()
  toRun();
}

//executing different functions
execute(3);
execute(2);
execute(1);

Answer №2

To streamline your code, you have two options:

vm.saveRecord = function() {
    var service = vm.valueTrue
            ? vm.otherValue
                ? doTaskA
                : doTaskB
            : vm.otherValue
                ? doTaskC
                : doTaskD;

    service.callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                // Handle successful response
            }
        }, function errorCallback(response) {
            // Handle error
        }
    )
};

Alternatively, you can group the functions in an object with keys as accessors.

vm.saveRecord = function() {
    var services = { doTaskA, doTaskB, doTaskC, doTaskD },
        service = vm.valueTrue
            ? vm.otherValue
                ? 'doTaskA'
                : 'doTaskB'
            : vm.otherValue
                ? 'doTaskC'
                : 'doTaskD';

    services[service].callEndPoint(param1, param2).then(
        function successCallback(response) {
            if(response) {
                // Handle successful response
            }
        }, function errorCallback(response) {
            // Handle error
        }
    )
};

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

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Convert a negative number to ASCII representation

Currently, I am attempting to extract the longitude and latitude of a user in order to utilize it in a Yahoo API query for obtaining the WOEID based on these coordinates. Subsequently, the WOEID will be passed through to a weather API call. My current pre ...

Working with npm in a Meteor 1.3 and angular1 environment (upgraded!)

Note: I am continuously revising this question as I make progress. Updates will be ongoing. After successfully upgrading my angular-meteor project (Meteor 1.2.1 + jade + ES6 js) to version 1.3, everything continues to work smoothly. Now, I am interested ...

Showing an array in angular.js

When sending data to a PHP file, the file processes it and performs an SQL search, returning a list of names in a for each statement. For example: Ryan, Jack, Billy, Sarah. However, when echoing the response in Angular, all the names are joined together l ...

Is there a way to efficiently remove deleted files from my Google Drive using a customized script?

After creating a function in Google Scripts to clear my trashed files, I ran it only to find that nothing happened. There were no logs generated either. function clearTrashed() { var files2 = DriveApp.getFiles(); while (files2.hasNext()) { var c ...

Secure your data by adding extra quotes during CSV export and IndexedDB import

Managing the export and import of an array of objects with a nested array inside involves using ngCSV, loDash, and PapaParse. This is how the array is structured: [ { arrival:"15.34.59", cancelled:"", comments:[{message: "test ...

What is the best way to sort a combination of numbers and text strings?

Within my table, I have column names enclosed in <th> tags and only numerical values inside <td> tags. When the user clicks on a <th> tag, the sorting algorithm organizes the values in ascending or descending order. .sortElements(function ...

Invoking AngularJS Function from Login Callback Script

Just getting started with angularjs and I have a logincallback function that is used for external login. This function returns the returnUrl, closes the externallogin pop up, and redirects back to the main page. function loginCallback(success, returnUrl) ...

In order to resolve this issue, I must eliminate any duplicate objects and then calculate the total sum using JavaScript

I have successfully removed the duplicates so far, but now I am stuck on how to sum the Total_Quantity. Is there a way to achieve this within the reduced method itself? Any help would be appreciated. Thank you. const test = [ { Item_Nam ...

How to effectively combine css() and delay() in jQuery?

fid: https://jsfiddle.net/k13sazuz/ Is there a way to create a delay chain for CSS rules using jQuery? $('.two').css('background','blue').delay(11800).css('background','red'); ...

Refresh a specific div element utilizing jQuery

I am facing a challenge with my data table in my Spring MVC project. I want to be able to update or remove data from the table without having to reload the entire page. Below is an example of the HTML div element: <div id="datatable"> </div> ...

Get the host name using Node.js server without using the 'req' parameter

Currently, I am utilizing req.headers.host to identify the host name of the server, which works well when dealing with incoming requests at the server. However, I am curious about how one can determine the host name without a request (i.e. without req). T ...

Ways to transfer property values between two instances of a component

Two datepicker components are present, one for "From" date and another for "To" date. If the "To" date is empty, I want to automatically update it with the value from the "From" date. I have considered using 'emit' on the value but I am unsure ...

Using TinyMCE editor to handle postbacks on an ASP.NET page

I came up with this code snippet to integrate TinyMCE (a JavaScript "richtext" editor) into an ASP page. The ASP page features a textbox named "art_content", which generates a ClientID like "ctl00_hold_selectionblock_art_content". One issue I encountered ...

Retrieving the variable value instead of a reference using Ajax in ASP

After spending nearly two days trying to figure out this code and researching every possible solution, I still haven't been able to get it to work properly. It's likely that I'm implementing it incorrectly or missing something, so I've ...

Selecting Texture Coordinates

My goal is to pinpoint where a user has clicked on a texture of an object to trigger a response by redrawing the texture. I've been able to achieve this by rendering my objects with a color-coded texture onto a separate render target and using gl.rea ...

Manipulating arrays in JavaScript through HTML processing

I'm encountering an issue while trying to send an array to a JavaScript function. Here's what I have so far: Within the controller: @data = [{date: '2014-08-17'}, {date: '2014-08-20'}].to_json In the view: <%= content_t ...

jQuery AJAX Triggered Only Once in Callback Function

I am facing an issue with the jQuery get function within my updateMyApps. The function works fine when called directly after it is declared. It successfully loops through the data and appends elements to the DOM. However, when I submit the form #addapplic ...

Looking to showcase website HTML code by simply clicking on a banner image?

I am looking to implement a feature where banner HTML code is displayed in a popup on website when the banner is clicked. For instance, an example of a banner could be: <img src="https://myweb.com/images/banners/1.gif"> Upon clicking the banner im ...

What methods can be used to secure Next.js API routes and prevent them from being directly accessed through the URL

I am seeking a solution for concealing the response data of next.js API routes when accessed through URL. I need to protect certain sensitive information from direct access by users. ...