Unlocking the Secrets of Returning Values in TypeScript

When checking the value of statusC and adding a new value for statusP, the process is as follows: If all statusC values are ACCEPTED => statusP will be set to ACCEPTED. If all statusC values are REJECTED => statusP will be set to REJECTED. In the case where statusC has both ACCEPTED and REJECTED values => statusP will be set to COMPLETED.

  1. Create an Enum type to use throughout the code.
enum Status {
    INPROGRESS = "INPROGRESS",
    ACCEPTED = "ACCEPTED",
    REJECTED= "REJECTED",
    COMPLETED = "COMPLETED"
}
  1. Declare variable 'a':
let a= [
    {
    name:"test 1",
    statusP : Status.INPROGRESS,
    detail:[
        {
            nameC: "Test 2",
            statusC: Status.REJECTED
        },
        {
            nameC: "Test 3",
            statusC: Status.ACCEPTED
        }
    ]
    }
];
  1. Check statusC values and update statusP accordingly*
const checkStatusC = a[0].detail.map(
        (item)=>{
            let b;
            b =  item.statusC;
            if(b===Status.ACCEPTED){
                a[0].statusP = Status.ACCEPTED
            }else if (b === Status.REJECTED){
                a[0].statusP = Status.REJECTED
            } else if({?}){
                a[0].statusP = Status.COMPLETED
            }
        }
    )

Please provide a condition for {?}

Answer №1

In this situation, it is recommended not to utilize the map method. The purpose of map is to map existing items to new items in an array. If you intend to assign a new value or values, it would be more appropriate to use the reduce method.

a[0].statusP = a[0].detail.reduce(
        (result, item)=>{
            //Cease further evaluation for status P
            if(result === Status.COMPLETED) {
                return result;
            }

            //The current state of status P differs from status C
            if(result && result !== Status.INPROGRESS && result !== item.statusC){
                result = Status.COMPLETED;
            } else {
                result = item.statusC; //REJECTED or ACCEPTED
            }
            return result;
        }
    , a[0].statusP) //Default value taken from status P

Alternatively, you can opt for the conventional iteration using for-of, which proves to be more efficient when coupled with a suitable break statement.

for(const item of a[0].detail) {
    //The present status D varies from status C
    if(a[0].statusP && a[0].statusP !== Status.INPROGRESS && a[0].statusP !== item.statusC){
       a[0].statusP = Status.COMPLETED;
       break; //Halt further assessment
    } else {
       a[0].statusP = item.statusC; //REJECTED or ACCEPTED
    }
}

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

Troubleshooting TestBed: Resolving the StatusBar Provider Error

After reading an informative article on testing Ionic2 projects with TestBed, I encountered difficulties when trying to replicate the example in my own environment. When attempting to initiate tests at Step 3, I encountered the error message stating "No pr ...

Investigating the issue: Why is my React Typescript canvas image resizing component producing small, fuzzy images from high-quality, large images

I have developed a small image resizer but am facing an issue with the output images being blurry, especially when working with large images. import React, { useState } from 'react'; interface PropsInterface { placeholder: string; resizeTo: ...

If the table spans multiple pages, a top margin will be added to ensure proper formatting. This feature is implemented using jspdf-autotable

I have encountered an issue with my PDF function where using multiple tables and the didDrawPage() hook to add headers and footers results in images being drawn multiple times in the header due to the multiple tables. To resolve this, I created a separate ...

Encountering an error message that says "ERROR TypeError: Cannot read property 'createComponent' of undefined" while trying to implement dynamic components in Angular 2

I am currently facing an issue with dynamically adding components in Angular 4. I have looked at other similar questions for a solution but haven't been able to find one yet. The specific error message I am getting is: ERROR TypeError: Cannot read ...

Converting types to "any" and encountering the error message "There are two distinct types with the same name, but they are not related."

I am encountering some challenges while trying to use an NPM module that I developed along with its Typescript typings in another application. To simplify the examples, I will omit properties that are not relevant to the issue at hand. Within my module&ap ...

Exploring Angular 5: Managing HTTP Headers and Utilizing URL Parameters

I am currently working on an Angular project that involves third-party authentication, which redirects to our app with additional information in the HTTP headers. Here are the questions I have: What is the best way to extract the information from the HT ...

Tips on displaying substitute text in Angular when an Iframe fails to load the content located at the src

Currently, I am working on an Angular 12 application and have a requirement to fetch content from an external site and display it within a modal popup. To achieve this, I am using the <iframe src="url"> tag to retrieve the content from a se ...

Tips for including a dash or hyphen in an input field after two digits in Angular 4

Struggling to format the date of birth input with dashes manually when entered by the user. The desired output should resemble "08-18-2019," but I'm having difficulty achieving this. public dateOfBirth: { year: number; month: number; day: number }; ...

Generating GraphQL Apollo types in React Native

I am currently using: Neo4J version 4.2 Apollo server GraphQL and @neo4j/graphql (to auto-generate Neo4J types from schema.graphql) Expo React Native with Apollo Client TypeScript I wanted to create TypeScript types for my GraphQL queries by following th ...

Is it possible to directly parse a multipart/mixed response without needing to first convert it into a string?

My current challenge involves receiving a multipart/mixed response over HTTP that includes JSON data and PDFs in byte format. Due to Angular's limitations with handling such responses, I have resorted to converting the response into a string using the ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

Having trouble getting the Typescript overload arrow function to function properly

(I am implementing strict null checks) The arrow function I have includes overloaded types: type INumberConverter = { (value: number): number; (value: null): null; }; const decimalToPercent: INumberConverter = (value: number | nul ...

Leverage the power of angular pipes to effortlessly add new DOM duplicates

I am currently working with angular 5 and I am looking for a way to dynamically duplicate DOM templates using a custom pipe: <div id="template" style="display:none;"> <a routerlink="{{parameter.route}}">here</a> </div> <nav& ...

The Angular controller fails to display any data when inserted within double curly braces on the HTML page

I have been working on a basic binding application using TypeScript. I created a controller called 'bugCtrl' and it appears to be functioning correctly in debug mode (with console.log and alert statements). Below is the HTML code from my page: & ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...

Ways to sort mat-select in alphabetical order with conditional names in options

I am looking to alphabetically order a mat-select element in my Angular project. <mat-select [(ngModel)]="item" name="item" (selectionChange)="changeIdentificationOptions($event)"> <mat-option *ngFor="let item of items" [value]="item"> ...

Tips for creating a Sequelize table with TypeScript the right way

My current challenge involves: interface PersonI { id?: number | null, firstName: string, lastName: string } @Table( { tableName: 'person', timestamps: true } ) class Person extends Model implements PersonI ...

Unable to prolong TypeScript document

As I develop a drag and drop interface, upon dropping a file, the native File is retrieved. To enhance this interface with additional information, I decided to explore various approaches. In my initial attempt, I utilized: interface AcceptedFile extends ...