Tips on excluding an object dynamically from the chaining process in JavaScript

In my object structure, both utils and utils.not have the same prototype with an exist method. To keep it simple, here is a clearer version:

var negative = true;
if(negative){
  //when negative===true, I want to run exist() through not object
  tests.utils.not.exist();
} else {
  tests.utils.exist();
}

Is there a way to dynamically exclude not from the chain without using an IF statement? For example, if I wanted to change the not object to another like positive, I could do it simply like this:

tests.utils[negative ? 'not':'positive'].exist();

But how can I dynamically exclude the not object from the chain without an IF statement? My current IF syntax works fine, but I'm curious if there is a more elegant way in JavaScript.

Answer №1

To eliminate the condition (if or ternary operator), one option is to conceal it within the exist() function:

tests.utils.exist(negative); // returns true or false

Allowing the exist method to determine the logic. However, I believe your current code is more straightforward and the explicit if statement enhances readability and comprehension. I do not view it as inelegant.

Answer №2

Uncertain if this information will be of help, however, you have the option to proceed as follows:

var actionItem = negative ? tests.utils.not : tests.utils;
actionItem.run();

Answer №3

Utilizing Proxies is a great way to establish default behavior and then customize their usage according to your needs. Check out this example below:

var handler = {
  get: function(target, name) {
    return target.hasOwnProperty(name) ? target[name] : target["default"];
  }
};

var p = new Proxy({
default : {
exists : function(){
return 1;
}
},
not : {
exists : function(){
return 2;
}
}       
}, handler);

let negative = false;

let x = p[negative === true ? "not" : "default"];
console.log(x.exists());

For further information, refer to the MDN documentation

Answer №4

When your method to be executed relies on the condition (negative === true), it is necessary to include the check. One way to optimize this code could be:

let customMethod = test.utils.exist; 
if (negative) {
  customMethod = test.utils.not.exist;
}

customMethod();

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

Tips for finding the *index* of distinct values in an array

My goal is to identify the indexes of unique values in an array. While I've come across various methods for removing duplicate values from an array, such as those found here: How to get unique values in an array I'm currently struggling to find ...

Having trouble getting ngAnimate to work properly?

I am facing an issue with ngAnimate dependency injection. For some reason, whenever I add ngAnimate as a dependency in my JavaScript code, it does not seem to work. It's definitely not the script... Here is the HTML code snippet: <!doctype html& ...

Is there a Node.js method that is similar to jQuery AJAX's .complete() function

In the process of creating a Node.js API to enroll a user in a different web application, I encountered an issue. As part of the registration flow, the API called by the Node app using request is being redirected with a status code of 301 to another API to ...

Triggering functions when the mouse wheel is in motion

I am new to utilizing javascript and jquery, and my knowledge is limited at the moment. I am attempting to create a script that will trigger different functions based on the direction of mouse wheel movements in a way that works across various programs. Ca ...

Create a Vue application that utilizes a promise to display content and then waits for user input

Seeking guidance for a design query, I am dealing with a JavaScript script that is heavy on logic. It is structured using promises as shown below: init() .then(result => doSomethingA(result)) .then(result => doSomethingB(result)) .then( ...

Tips for displaying a combobox popover from @reach/combobox within a MUI dialog element

I've been attempting to integrate a map from the Google Maps API and a combobox popover from @reach/combobox within a MUI dialog component. However, I've encountered an issue where the combobox popover isn't displaying. After some investigat ...

Mithril does not automatically refresh the view

After modifying the prop values in Mithril, the view is not automatically redrawn. To update my prop upon pressing a button, I use the following code: something.vm.test(something.vm.test() + 1); Although this code updates the prop value, the changes ...

Embedding a YouTube video in an iframe triggers numerous cautionary notifications in the Chrome browser

I have a website with numerous YouTube links embedded in iframes. However, the page loads extremely slowly and some of the YouTube images do not load at all. The website is built using PHP. Even with just 7 YouTube links, the Chrome browser generates over ...

Autofill class names in VS Code for Next.js using Emmet

How can I modify Emmet autocomplete to change from className="" to className={styles.}? If it is possible, could you please guide me on how to achieve this? Alternatively, if modifying the autocomplete feature is not an option, is there a way to create a ...

How can I show the most recent x floating point values on a chart using ChartJS?

I'm currently working on a Vertical Bar Chart using react-chartjs-2. I have an array of numerous float numbers saved. My attempt to utilize the chartjs callback option to only show the last value on the graph failed. The problem lies in the fact th ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

choose the li element that is located at the n-th position within

Need help with HTML code <div class="dotstyle"> <ul> <li class="current"><a href="javascript:void(0)"></a></li> <li><a href="javascript:void(0)"></a></li> <li><a href="javasc ...

Tips for addressing flickering issues when scrolling on your device

I am facing an issue with two elements that are set to a fixed position on the page. When these elements reach the bottom of the page, I want them to revert back to a static position using JavaScript. The problem occurs when trying to scroll by clicking a ...

Trouble with AJAX/Live Search functionality

My files are ready for examination: The PHP File for Backend Search Functionality: <?php require "../sinfo.php"; function chk_phone($orig) { return preg_replace("/[^0-9]/","",$orig); } $s = $_POST["s"]; $sql = "SELECT * FROM requests WHERE id LI ...

How can I retrieve data from the Hasura hook "useQuery"?

As a newcomer to web development, I am attempting a simple 'GET' request using the "useQuery" hook from Hasura. However, I am encountering difficulties accessing my data. Strangely, the query has been successfully tested on the Hasura console wit ...

Uploading and previewing multiple images on a canvas

After successfully creating single upload for images and placing them on canvas as seen in http://jsfiddle.net/StJnY/, I am now looking to adapt the script for multiple image uploads. Here is how I plan to modify the script: JS : $(function () { $(&a ...

Load external JSON file using THREE.JSONLoader (excluding models)

I'm attempting to use THREE.JSONLoader to load a JSON file that contains coordinates, not a JSON model. Here's what I'm aiming to achieve: var loader = new THREE.JSONLoader(); loader.load("coordinates.json", function(result) { console.log ...

What is the best way to add permissions to each role in JavaScript?

I have been attempting to dynamically add data to an HTML table using JavaScript. The data consists of roles and their corresponding permissions, which are retrieved using Laravel's ORM. I have tried utilizing a nested each jQuery function to append t ...

Fluid sifting and interactive webpage

I'm almost done with my website, but I'm facing a problem. There are 3 blocks of text on my page - 2 static and 1 dynamic. When I click a button, the page should change, which is working fine. However, when I added smooth scroll to the website, ...

Shuffle the contents of various div elements, conceal one, reveal another

I am currently working with a menu that uses the loadContent function to load pages into the #main div. This allows me to change the content of the page while keeping the menu intact. <ul> <li class="page1" onclick="loadContent('page1.php ...