Maximizing conditional evaluation in typescript

I have the following JavaScript code where I am displaying different status based on the response key from an API. Is there a more efficient approach to optimize this code so that I don't have to check each case with IF, especially if the number of statuses increases?

if (data.shippingStatus) {
  let shippingStatus = data.shippingStatus.toString();
  
  const statusMap = {
    "AWAITING_SHIPMENT": "Awaiting Shipment",
    "SHIPPED": "Shipped",
    "DELIVERED": "Delivered",
    "CANCELLED": "Cancelled"
  };
  
  shippingStatus = statusMap[shippingStatus] || "";

  resData.push(setData(data.shippingStatus ? shippingStatus : ""));
}

Answer №1

Consider using an object mapper for this task:

const shipmentStatusMapper: {[key:string]: string} = {
  AWAITING_SHIPMENT: "Awaiting Shipment",
  SHIPPED: "Shipped",
  DELIVERED: "Delivered",
  CANCELLED: "Cancelled"
};

if (data.shippingStatus) {
  let shippingStatus = data.shippingStatus.toString();
  resData.push(setData(data.shippingStatus ? shipmentStatusMapper[shippingStatus] : ""));
}

UPDATE: Included a type declaration in the mapper for better clarity.

Answer №2

When it comes to addressing your query, there are various approaches that can be taken. If you're specifically seeking a robust solution for the current issue of mapping values, one option is to either create an object mapper as suggested in other responses or simply develop a straightforward function to format your string in a certain way.

var example = "AWAITING_SHIPMENT";
example = example.toLowerCase()
    .split('_')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');
console.log(example);

However, if you wish to explore this topic from a broader perspective, employing dynamic dispatch through polymorphism could be advantageous. Here's an illustration demonstrating how polymorphism can alter behavior based on type.

Answer №3

My approach involves splitting the status string using underscores and then capitalizing each word before returning a new formatted status as per specifications.

// Sample Data

const data = {
  shippingStatus: "AWAITING_SHIPMENT"
}

// Updated Solution

if(data.shippingStatus){
  const { shippingStatus } = data;
  
  const status = 
  shippingStatus.split('_') 
  .map(string => string.charAt(0).toUpperCase() + string.slice(1).toLowerCase())
  .join(" ");
  
  console.log(status)
  
  // Avoid redundant checks by directly processing the status within the if condition
  // For example: resData.push(setDate(status))
  
}

Answer №4

Creating a map to define possible statuses:

let orderStatuses = {
   'AWAITING_SHIPMENT': 'Awaiting Shipment',
   'SHIPPED': 'Shipped',
   ...
};

responseData.push(setData(order.shippingStatus ? orderStatuses[shippingStatus] : ""));

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

Accessing information from an Angular Elements Web Component using vanilla JavaScript

I am in the process of creating several WebComponents that I plan to utilize across various libraries and frameworks, with a primary focus on plain vanilla JavaScript. My current consideration is to implement Angular Elements for this purpose, and I have a ...

Adjustable <a> component

There is this element: <a id="lnkViewEventDetails" class="psevdo calendar-event event" style="height: 126px;" href="/someurl/895?responseType=5" onclick="event.stopPropagation();"> I am trying to make it resizable using JQuery UI: $("#lnkViewEvent ...

retrieve data from the API response using a node request

I initiated an API request using the request method. Everything seems to be functioning properly, but I am encountering difficulty extracting the results from the response. The snippet of my code in question is as follows: app.get('/events/:query&a ...

Guide on effectively converting a table of tuples to an array of objects utility function (similar to zip) while preventing the merging of all values in typescript version 5.2.2

Almost there, but stuck on the final TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol compiler error. Here's a nifty utility function called rowsToObjects() that many developers have probably come up with at some point, ...

Is there a way to update the state for a specific location on a map?

I have a requirement to update the quantity of a product by using setCount. let [product.quantity, setCount] = useState(product.quantity); Implementing increment and decrement functions for product.quantity const increaseQuantity = () => { setCoun ...

What is the best way to convert line breaks within a textarea to use <br/> instead?

In my project, I have created a textarea along with a button. This button is designed to replace line breaks within the textarea with <br /> tags. Sample Code: var gtcontbtnafterTA = document.getElementById("contbtnafterTA"); var gtRequesttextare ...

Harness the Power of Asynchronous Binding in Knockout.js

I'm really struggling to figure out how to asynchronously bind my cascading Select2 drop-down fields using knockoutJS. Everything works perfectly fine when the data is static within the function, but as soon as I introduce an asynchronous ajax call, ...

Learn the steps for retrieving master page properties within an aspx page

lblTitle = ((Default)_page.Master).messageBoxTitle; lblError = ((Default)_page.Master).messageBoxMsg; btn1 = ((Default)_page.Master).button1; btn2 = ((Default)_page.Master).button2; btn3 = ((Default)_page.Master).button3; imgIcon = ((Default)_page.Master). ...

What is the proper syntax for specifying a specific field in a generic class?

type Specific = {field: 'add'} | {field:'remove'}; function add(value: Specific) {} // Ensures value.field === 'add' function remove(value: Specific) {} // Ensures value.field === 'remove' How can I restrict functi ...

Ensure that the value is updated upon clicking on the radio buttons and store the value in a session variable for

I'm working on a feature that involves two radio buttons: one for shipped and the other for not shipped. The requirement is that when the first radio button is clicked, an amount of 100 should be added to the total price. If the second radio button is ...

Techniques for transferring child properties and values to parent components upon the screen being initialized

Is there a way to pass property values from a child component to a parent component when the react app is first loaded? In my scenario, I have a parent component named app.js that renders a home component containing a JSON component. Initially, upon loadi ...

Angular's Spanning Powers

How can I make a button call different methods when "Select" or "Change" is clicked? <button type="button" class="btn btn-default" *ngIf="!edit" class="btn btn-default"> <span *ngIf="isNullOrUndefined(class?.classForeignId)">Select</spa ...

What is the best way to manage a file upload process?

What is the process for handling a file uploaded through curl in an express js action/route? router.route('/images') .post (function(req, res) { res.status(200); res.json({ message: 'file uploaded' }); }); app.u ...

The jsx file is not being parsed by Webpack

In my current project, I am working with a JSX file that contains React code. import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { render () { return <p> Hello React!</p>; ...

When using Router.push() in next.js, the error TypeError: products.map is not a function may arise

Currently, I am implementing redux saga in my project. Here is how the state looks: const productList = useSelector((state: RootState) => state.productList); const { loading, error, products, page, pages } = productList; In the useEffect hook, I dispa ...

Tips for utilizing console log within a react form component

I'm currently exploring ways to communicate with a React form in order to provide it with an object.id for updating purposes. While I can successfully console log the object.id within the update button and modal, I am struggling to confirm if the val ...

Tips for adjusting the height of an iframe to ensure that all content is responsive and contained within a div set to 40% height

I am having issues with setting the height of an iframe that displays a PowerBI dashboard. My specific requirements are: The content within the iframe should be contained within a div that has a height of 40% and sets all its contents to a height of 100% ...

"Enhancing Angular 2 with a robust HTTP retry system

My API uses token-based authentication for security. Once a user successfully signs in, two tokens (access and refresh) are stored in the browser's local storage. The access token contains all the necessary information for server-side authorization an ...

What are the steps to turn off unwanted autocomplete suggestions in VS Code?

I've noticed some bizarre autocompletion suggestions popping up in VS Code that don't align with my TS typings. While the expected suggestions are displayed at the top of the list, there are also random options like #endregion, #region, and async ...

Utilizing Javascript to extract information from JSON

After making an AJAX call, I have received a string in JSon format: {status:OK,addresses:[0,1,2,3,4,5]} In order to convert it into a JSon object, I tried using the following line of code: var jsonObj = eval(jsonString); However, this resulted in an ex ...