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

What is the maximum number of groupings that can be created from a set of numbers within a

I'm trying to figure out how to handle a specific task, but I'm running into some obstacles. When adding numbers to clusters, a number is considered to belong to a cluster if its distance to at least one existing number in the cluster is within a ...

Am I going too deep with nesting in JavaScript's Async/Await?

In the process of building my React App (although the specific technology is not crucial to this discussion), I have encountered a situation involving three asynchronous functions, which I will refer to as func1, func2, and func3. Here is a general outline ...

Information gathered from checkboxes and dropdown menus

When gathering information from my form fields, I know how to capture data from input fields using this code: 'formData' : { 'timestamp' : '<?php echo $timestamp;?>', 'token' : '<?php echo md5(&a ...

When the mouse is moved, display a rectangle on the canvas

I am having an issue with drawing a rectangle on canvas. The code below works fine, except that the path of the rectangle is not visible while the mouse is moving. It only appears when I release the mouse button. Any assistance would be greatly appreciate ...

Error: ajax is not defined and needs to be declared (repeated twice)

Currently, I have a form that requires processing using Ajax. <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script> <div class="column1"> <form class="form box" action="javascript:networkCheck();" ...

Launch a bootstrap modal from a different webpage

If you're looking to open multiple modals with different content displayed from HTML files, check out this example below: <div id="how-rtm-works" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" ...

The Next.js developer encounters an issue where the build fails due to a ReferenceError on a client component, stating that "window

Just starting out with nextjs, I'm sticking to using only the basic features without diving into any advanced functionalities. During the next build process, I encountered an issue where 6 paths failed because of a ReferenceError: window is not defin ...

The challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

Tips for customizing your MUI slider design

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

What is the formula for determining the percentage of transparent area on a canvas?

In my Ionic 4 drawing app, I have incorporated an image of the number 1 on the canvas using drawImage and made the background transparent. If users (typically kids) draw outside the number 1 image, the accuracy percentage will decrease. While searching for ...

Changing the templateUrl of a directive on the fly using the controller

How can I dynamically pass the templateUrl for the app_modal directive from the "ServerController" controller to allow for different templates for different modals? I have included the URL as an attribute in the "app-modal" tag used in the server_group.htm ...

Mastering advanced String templating using loops and control statements in Javascript

During runtime, I receive an array similar to the example below: var colors = ['red', 'green', 'blue']; I then need to create a JSON String that looks like this: { "color" : { "name" : "foo", "properties ...

Choosing the Right Language for AngularJS 2: TypeScript, JavaScript, or Dart?

AngularJS 2 is on the horizon, and the documentation recommends three languages: Typescript, Javascript, and Dart. As someone who primarily works with Javascript EcmaScript 5, I'm curious about the strengths and weaknesses of these three options. Cu ...

Having trouble retrieving the attribute of an appended element in jQuery?

I am facing an issue where I am unable to retrieve the ID-attribute of an element that has been appended into my HTML. Each time I try, the result is always 'undefined'. How can I resolve this problem? jQuery('form#formular').append(&a ...

Customize the text that appears when there are no options available in an Autocomplete component using React

Recently, I came across this Autocomplete example from MaterialUI that caught my attention. https://codesandbox.io/s/81qc1 One thing that got me thinking was how to show a "No options found" message when there are no search results. ...

Is there a way to successfully submit multiple locations, each separated by commas, through the multipart form?

Here is my HTML form: <form method="POST" enctype="multipart/form-data" v-on:submit.prevent="handelSubmit($event);"> <div class="clear"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="form ...

Let us know when the information on a different tab is updated

I have multiple tabs and I want to indicate when a change occurs on another tab that the user hasn't clicked. For example, if the user hits the run button while on the Data pane, I would like the Errors tab to change to red to show that there was a ch ...

Tips for placing multiple images onto one canvas

I am currently working on a web application that allows users to create sketches, define their positions and sizes, and then save them to a database. In another section of the website, I aim to retrieve these images and display them on a single canvas. To ...

The importance of using clearTimeOut in debounce function

Could you explain the importance of using clearTimeout in debounce function? Let's take a look at the code below: const saveInput = (name) => { console.log('saveinput ', name); } const debounce = (fn, timeout = 3000) => { ...

Implementing the MVC pattern in the app.js file for a Node.js and Express web application

After completing several tutorials on nodejs, mongodb, and express, I have gained a solid understanding of the basics such as: The main controller file being app.js. Third party modules stored in their designated node_modules directory. Template files pl ...