打字稿重构功能

时间:2020-02-05 07:09:55

标签: typescript ecmascript-6 refactoring angular5

如果使用变量 i ++ ,我正在使用声纳,并且最后一次闻到臭虫味。我需要以某种方式重构此代码,以免冗余:

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;
  }

1 个答案:

答案 0 :(得分:0)

也许这可以帮助您?

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

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

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

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

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

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

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

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

Playground

相关问题