Revamping TypeScript function

Having an issue with a bug smell in my code while using Sonar. The problem lies in the redundancy of incrementing the variable i++ within each if statement block. Looking for suggestions on how to refactor this code more efficiently:

private getDetailedUsageUrl(startDate: string, endDate: string, trafficType: string){
    this.logsProvider.debugLog(this.logTag, 'getDetailedUsageUrl');

    let url = this.detailedUsageServiceUrl;
    let i = 3;

    if (startDate !== null){
      url += 'startDate=$' + i;    
      i++;    
    }

    if(endDate !== null){
      url += '&endDate=$' + i;
      i++;
    }

    if (trafficType !== null){
      url += '&trafficType=$' + i;
      i++;
    }
    return url;
  }

Answer №1

Perhaps this solution can be of assistance to you?

function generateCustomUrl(startDate: string | null = null, endDate: string | null = null, trafficType: string | null = null): string {
    // this.logsProvider.debugLog(this.logTag, 'generateCustomUrl');
    // let url = this.customServiceUrl;
    const url = 'http://example.com/?'
    const offset = 3;

    let params: any = {
         startDate,
         endDate,
         trafficType
    };

    params = Object.keys(params)
        .filter((key) => params[key] !== null)
        .map((key, inx) => key + '=$' + (offset + inx));

    return url + params.join('&');
}

// http://example.com/?startDate=$3&endDate=$4&trafficType=$5
console.log(generateCustomUrl('a', 'b', 'c'));

// http://example.com/?endDate=$3&trafficType=$4
console.log(generateCustomUrl(null, 'b', 'c'));

// http://example.com/?startDate=$3&trafficType=$4
console.log(generateCustomUrl('a', null, 'c'));

// http://example.com/?startDate=$3&endDate=$4
console.log(generateCustomUrl('a', 'b', null));

Practice

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

Best approach to inform pages about a variable update in Ionic

Imagine a scenario where we have a page called ListItemPage displaying a list of items: Within the ts file, there is a variable defined as items: any = []; In the html file, we find <ion-item *ngFor="let item of items"> Users can click on a (+ ...

What is the method for inserting two dashes within a number?

For the output, I am looking to showcase a number in the following format => 979-9638403-03. At present, the number appears like this => 979963840303. portfolio.ts export class Portfolio { ... DEPO: number; /* DEPO */ const ...

Having difficulty troubleshooting the /app router application on version 13.4.x

Having trouble debugging a server-side process in my Next.js app that uses the /app router. To reproduce the issue, simply create a new Next.js app with npx create-next-app and select the app router option. I've attempted to attach a debugger to the ...

The type '{ id: string; }' cannot be assigned to the type 'DeepPartial<T>'

In my code, I am attempting to create a generic function that abstracts my repository infrastructure for creating a where clause. export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export int ...

Angular 7: Resetting multiple dynamically generated checkboxes back to their original state with the click of a button

I have created a child component that contains 3 checkboxes, generated dynamically using ngFor, along with Apply and Cancel buttons. In the parent template, I include the selector tag for the child component. The parent component accesses this child compo ...

Observing Array behaviors in TypeScript

Struggling to generate an observable from an array due to the recurring error message (A tuple type element list cannot be empty). Despite multiple attempts, I'm unable to resolve this issue. listDonationsHistory(): Observable<[]> { const ...

Exploring the variance in performance between lodash's "get" function and traditional "if else" clauses

Imagine you have a TypeScript object with the possibility of elements being undefined. Navigating through a deeply nested structure requires multiple comparisons against undefined values. I wanted to examine the performance difference between using regula ...

Designing a TypeScript class that incorporates an interface

Struggling to grasp the correct syntax, I am looking to incorporate an interface into my project. The desired interface for implementation is as follows: interface Test { [name : string] : (source : string) => void; } My understanding is that this ...

Generating Legible JavaScript Code from TypeScript

I am looking to maintain the readability of my compiled JS code, similar to how I originally wrote it, in order to make debugging easier. However, the typescript compiler introduces several changes that I would like to disable. For instance: During compi ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Establish a default value for a TypeScript generic Type: distinguishing between 'unknown' and 'any'

An interface has been created with a parameter that takes a generic type input named Data export interface MyStructure<Data> { id: string; data: Data; } The goal is to allow the Data type to be optional in order to support scenarios like: functi ...

Customize the form using a custom component in react-hook-form: setting a default value

I have been learning ReactJS + TypeScript for 3 months now. Recently, I have a question about using react-hook-form (v7) to edit a form. I want to integrate my custom component into the form and I managed to do it on my own! Here is a snippet of my form p ...

"Utilize Protractor to access individual instances of Angular directives and components in your

I'm currently working on an Angular project. During my unit tests using karma and jasmine, I can easily access component instances and directives through ComponentFixture and DebugElement. Would it be possible to achieve the same functionality while ...

Using Typescript with Gulp 4 and browser-sync is a powerful combination for front-end development

Could use some assistance with setting up my ts-project. Appreciate any help in advance. Have looked around for a solution in the gulpfile.ts but haven't found one yet. //- package.json { "name": "cdd", "version": "1.0.0", "description": "" ...

How can I access internal.Writable within the basic-ftp NodeJS module using TypeScript?

After examining the API documentation of the basic-ftp module, I came across the following: downloadTo(writableStream | localPath, remotePath, startAt = 0): Promise<FTPResponse> However, when utilizing the module in a TypeScript project, the method ...

Working with e.charcode in TypeScript allows for easy access to

I'm having trouble understanding why this code snippet is not functioning as expected. const addRate = (e: { charCode: KeyboardEvent }) => { if (e.charCode >= 48) { ... } } The error message I receive states: 'Operator '>=& ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

What could be causing the 'controls' property to be undefined when using form: FormGroup in an Angular 11 component?

Just diving into Angular 11 and getting to grips with TypeScript.. I'm trying to access the 'controls' property in a specifically defined 'FormGroup' variable. But for some reason, it keeps saying that the property is undefined... ...

Any class that utilizes the interface `IGeneratable` must include an `IGeneratorConstructor<T>` where `T` represents the class implementing the `IGeneratable` interface

My goal is to enforce the requirement that any class implementing the IGeneratable interface must also provide a IGeneratorConstructor<T>, where T represents the class implementing IGeneratable. Is this achievable in TypeScript (specifically version ...

Angular 2 component hierarchy with parent and child components

Currently, I am in the process of learning typescript and angular2. My attempt to incorporate parent and child components into my fiddle has not been successful. Despite conducting some research, I have encountered an error that states: Uncaught ReferenceE ...