What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript?

private getProductName(productType: string): string {
    let productName = 'Product not found';

    this.deal.packages.find(p => p.isSelected).dealProducts.find(dp => (dp.children.length > 0 && dp.children[0].product.productTypeCode == productType)) ? 
      productName = this.deal.packages.find(p => p.isSelected).dealProducts.find(dp => (dp.children.length > 0 && dp.children[0].product.productTypeCode == productType)).children[0].product.name : 
    this.deal.packages.find(p => p.isSelected).dealProducts.find(dp => (dp.children.length === 0 && dp.product.productTypeCode === productType)) ?
      productName = this.deal.packages.find(p => p.isSelected).dealProducts.find(dp => (dp.children.length === 0 && dp.product.productTypeCode === productType)).product.name :
    null;

    return productName;
}

Answer №1

The current code implementation suffers from inefficiency due to unnecessary redundancy in finding the same element multiple times, resulting in looping multiple times.

To improve readability and efficiency, I restructured the code into separate parts. It now loops only once over the object to identify items with children and those without children, utilizing a ternary operator to streamline this process.

Additionally, the updated code now efficiently determines whether the identified item is a child or not before retrieving the object.

// Retrieve the selected package products
var selectedPackageProducts = this.deal.packages.find(p => p.isSelected).dealProducts;

// Check if the product type belongs to the children or parent (if no children)
const selectedProduct = selectedPackageProducts.find(dp => 
    dp.children.length > 0 ? 
    dp.children[0].product.productTypeCode === productType :
    dp.product.productTypeCode === productType)

// Use children if available, otherwise refer to the parent
const productObj = selectedProduct && selectedProduct.children.length ? 
    selectedProduct.children[0] :
    selectedProduct;

// Obtain the name of the product 
const productName = productObj && productObj.product.name

Answer №2

Stepping into what now feels like a battlefield of conflicting opinions, I willingly put myself at risk to demonstrate two important points.

  1. The pursuit of clean code and readability is not merely about asserting superiority or flaunting expertise. It serves the purpose of maintaining one's sanity and well-being (as well as that of the entire team), especially for those tasked with maintaining the code in the near future and beyond.

  2. Through refactoring the original poster's code to enhance readability, several objectives are accomplished:

  • Eliminating redundant and unnecessary data retrievals, focusing only on the essential ones and doing so efficiently.
  • Clarifying the nature of the data being handled, making it easier to identify and modify during future refactorings.
  • Successfully meeting the OP's requirement for a return value based on nested ternary operators, a task made considerably more challenging without prior cleanup.

private retrieveProductName(productType: string): string {
  const defaultName = 'Product not found';

  const selectedPackageProducts = this.deal.packages
    .find(p => p.isSelected).dealProducts;

  const chosenProducts = selectedPackageProducts
    .find(dp => (dp.children.length > 0 && dp.children[0].product.productTypeCode === productType));

  const selectedProduct = !chosenProducts && selectedPackageProducts
    .find(dp => (dp.children.length === 0 && dp.product.productTypeCode === productType));

  return chosenProducts
    ? chosenProducts.children[0].product.name
    : (selectedProduct ? selectedProduct.product.name : defaultName);
}

Answer №3

Instead of writing the traditional syntax: IF condition THEN do_a ELSE do_b, you have the option to streamline your code using ternary operators in a similar manner.

(condition) ? do_a : do_b;

Here is a concrete example specific to your scenario:

private getProductName(productType: string): string {
    return (this.deal.packages.find(p  => p.isSelected).dealProducts.find(dp => (dp.children.length > 0 && dp.children[0].product.productTypeCode == productType)))
 ? this.deal.packages.find(p  => p.isSelected).dealProducts.find(dp => (dp.children.length > 0 && dp.children[0].product.productTypeCode == productType)).children[0].product.name
 : (this.deal.packages.find(p  => p.isSelected).dealProducts.find(dp => (dp.children.length === 0 && dp.product.productTypeCode === productType)))
 ? this.deal.packages.find(p  => p.isSelected).dealProducts.find(dp => (dp.children.length === 0 && dp.product.productTypeCode === productType)).product.name
 : 'Product not found';
}

By the way, it is advisable to consider extracting methods for do_a and do_b for better code organization.

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

Using Typescript: How to pass a function as an argument in another function

In my angular application, I am working on the following setup: this.myServiceOne.getDataOne().subscribe((res => {this.variableOne= res})); this.myServiceTwo.getDataTwo().subscribe((res => {this.variableTwo= res})); this.myServiceThree.getDataThree( ...

Link a function to a button in a 3rd party library

Whenever I click a button, there is a possibility of an alertify alert window appearing randomly. The alertify alert popup serves as a more aesthetically pleasing alternative to the traditional javascript Alert. Alertify library Below is a snapshot depic ...

What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response: {username:'patrick',userid:'3636363',position:'employee'} {username:'patrick',userid:'3636363',position:&a ...

Issues with rendering in-line styles in ReactJS after a state update

I'm currently working on implementing a basic state change for a button in React. 'use strict'; class ReactButton extends React.Component { constructor(props) { super(props); this.state = {hovering: false}; } onClick() { ...

Adjust the location.hash and then navigate using the Back button - Internet Explorer displays unique behavior compared to other web browsers

When updating `location.hash`, all browsers behave correctly by only changing the URL without refreshing the page. However, pressing the Back button in Internet Explorer and other browsers results in different behaviors. IE fails to update the history wit ...

Identifying the length of a division element following its addition

I'm facing difficulties in detecting the length and index of the dynamically appended div. I have researched extensively and found a solution involving MutationObservers, but I am unsure if it is necessary for this particular issue. Let's focus ...

Is an audio player/playlist necessary for showcasing a mix engineer's skills in their

As a newcomer to the world of web development with some background knowledge from school, I work as a mix engineer and have created a portfolio website. Previously, I utilized Soundcloud and Spotify's API to showcase my mixes/songs, but the external J ...

Looking to empty a textbox, give it focus, and avoid triggering an ASP.NET postback all with a single click of a

I am working on an ASP.NET project and I have a simple HTML button. When this button is clicked, my goal is to clear textbox1, set the focus on textbox1, and prevent any postback from occurring. However, I am running into an issue where preventing postba ...

The CSS legend for a FLOT plot chart is being unexpectedly replaced

I am currently exploring the FLOT plot tool and facing difficulty with the legend display. It seems that the CSS styling for the legend is somehow being overridden in my code, resulting in an undesirable appearance of the legend: Even when I try to specif ...

Is there a way to alter the color of options within a select tag when hovering the mouse over them

After searching through multiple websites, I couldn't find a solution on how to change the option background color on hover from blue to green. The screenshot provided below illustrates what I am requesting for in a clearer manner. I attempted to use ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

There are no HTTP methods available in the specified file path. Make sure to export a distinct named export for each HTTP method

Every time I attempt to run any code, I encounter the following error message: No HTTP methods exported in 'file path'. Export a named export for each HTTP method. Below is the content of my route.ts file: import type { NextApiRequest, NextApi ...

Node.js and Socket.IO: Managing responses

In a unique scenario, the web page is initially served using HTTP. When the submit button is clicked, data is sent to the server and multiple web services are executed, which may take some time. The challenge is to quickly display the response page and the ...

What ways can we implement identification features in Flutter Web applications, such as adding an ID or name property?

While developing a Flutter Web application, I am exploring a Web-UI-Testing framework that is Selenium-based. Unfortunately, I am struggling to locate an HTML element that represents a specific flutter widget by its id or name attribute. The widget key doe ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...

Enhancing the tooltip inner content in Bootstrap with a description:

Can you help me troubleshoot the code below? I am trying to add a description to numbers in my tooltip, but it doesn't seem to be working. Here is the HTML: <input id="contract-length" class="slider slider-step-2 slider-contract-length" ...

The incorrect order of CSS in NextJS production build

When working on my project, I make sure to import CSS files both from local sources and node modules: //> Global Styling // Local import "../styles/globals.scss"; // Icons import "@fortawesome/fontawesome-free/css/all.min.css"; // Bootstrap import "boot ...

The AngularJS element fails to display on the screen

I am currently learning AngularJS and I am struggling to understand how components are linked to the view in the tutorial. I have created a component that is quite similar: angular.module('phonecatApp').component('nameList', { temp ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...