将If-Else语句转换为Switch语句

时间:2016-11-28 17:33:55

标签: javascript if-statement switch-statement

我最近使用if-else语句在CodeWars中完成了一个问题,但我想重试它并使用switch语句。太糟糕了,它没有像我想象的那样工作!

我正在解决的问题是在铁人三项运动员已经完成的距离内,并根据运动员是应该游泳,骑自行车还是以长度值运行来返回显示钥匙的物体比赛的进行。

我的If-Else解决方案:

function iTri(s) {  
  var triLength = 140.60;  
  var result = {};  
  var str = ' to go!';  
  var lengthLeft = (triLength - s).toFixed(2);  

  if (s === 0) {
    return 'Starting Line... Good Luck!';
  } else if (s <= 2.4) {
    result.Swim = lengthLeft + str;
  } else if (s <= 114.4) {
    result.Bike = lengthLeft + str;
  } else if (s < 130.60) {
    result.Run = lengthLeft + str;
  } else if (s < 140.60) {
    result.Run = 'Nearly there!';
  } else {
    return 'You\'re done! Stop running!';
  }
  return result;
  }

(非工作)Switch语句:

function iTri(s){
  let tri = (2.4 + 112 + 26.2).toFixed(2);
  let left = tri - s;
  let str = ' to go!'
  let result = {};

  switch(s) {
    case (s === 0):
      return "Starting Line... Good Luck!";
      break;
    case (s <= 2.4):
      result.Swim = left + str;
      return result;
      break;
    case (s <= 114.4):
      result.Bike = left + str;
      return result;
      break;
    case (s <= 130.60):
      result.Run = left + str;
      return result;
      break;
    case (s < 140.60):
      result.Run = 'Nearly there!';
      return result;
      break;
    default:
      return 'You\'re done! Stop running!';
  }
}

这些是测试:

Test.describe("Example tests",_=>{
Test.assertSimilar(iTri(36),{'Bike':'104.60 to go!'});
Test.assertSimilar(iTri(103.5),{'Bike':'37.10 to go!'});
Test.assertSimilar(iTri(2),{'Swim':'138.60 to go!'});
});

输出:

✘ Expected: '{ Bike: \'104.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Bike: \'37.10 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''
✘ Expected: '{ Swim: \'138.60 to go!\' }', instead got: '\'You\\\'re done! Stop running!\''  

将它转换为switch语句也值得吗?这样做有什么好处/缺点,就像/ vs vs switch一样?

2 个答案:

答案 0 :(得分:1)

  

尝试将其转换为switch语句是否值得?

没有。 URL <- read.csv("~/Desktop/LW_url.csv", header=T) URL %>% html_nodes("table", ".wages_table .even .col-NaN , .wages_table .results .col-NaN") %>% .[[1]] %>% html_table() 仅在您有多个完全匹配时才有用。情况并非如此。

答案 1 :(得分:0)

如果你稍微解决问题,那么可以像这样使用开关。您的开关非常接近

int res;
char errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle;
struct bpf_program fp;
bpf_u_int32 net = PCAP_NETMASK_UNKNOWN;
struct pcap_pkthdr *header;
const u_char *pkt_data;
struct timeval oldTimeUploadStruct;
struct timeval oldTimeDownloadStruct;

const char *filter_exp = // big filter of mine

handle = pcap_open_live("wlan0", 65535, 0, 1000, errbuf);
if (handle == NULL) {
    fprintf(stderr, "Couldn't open device wlan0: %s\n", errbuf);
    return;
}

// Compile and apply the filter
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
    fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
    pcap_close(handle);
    return;
}
if (pcap_setfilter(handle, &fp) == -1) {
    fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
    pcap_close(handle);
    return;
}

gettimeofday(&oldTimeUploadStruct, NULL);
gettimeofday(&oldTimeDownloadStruct, NULL);

long long oldTimeUpload = (oldTimeUploadStruct.tv_sec * 1000000) + oldTimeUploadStruct.tv_usec;
long long oldTimeDownload = (oldTimeDownloadStruct.tv_sec * 1000000) + oldTimeDownloadStruct.tv_usec;

// stopLogging is a flag set to false from child process before detaching this thread; 
// when connection is over, the flag is set to true and this loop breaks
while ((res = pcap_next_ex(handle, &header, &pkt_data)) && (stopLogging == false)) {

    // 0 if the timeout set with pcap_open_live() has elapsed.
    // In this case pkt_header and pkt_data don't point to a valid packet
    if (res == 0) {
        continue;
    }

    if (packet is in upload) {
        long long timestamp = (header->ts.tv_sec * 1000000) + header->ts.tv_usec;
        long long delay = timestamp - oldTimeUpload;
        std::stringstream mylogstream;
        // creating string to log: I omitted some variables
        // like IP addresses and ports for brevity
        mylogstream << host << " UPLOAD " << timestamp << ' ' << header->caplen << ' ' << delay;
        // logging captured packet
        std::string mylog = mylogstream.str();
        fs << mylog;
        oldTimeUpload = timestamp;
    }

    else if (packet is in download) {
        long long timestamp = (header->ts.tv_sec * 1000000) + header->ts.tv_usec;
        long long delay = timestamp - oldTimeDownload;
        std::stringstream mylogstream;
        mylogstream << host << " DOWNLOAD " << timestamp << ' ' << header->caplen << ' ' << delay;
        // logging captured packet
        std::string mylog = mylogstream.str();
        fs << mylog;
        oldTimeDownload = timestamp;
    }
}

if(res == -1)
    printf("Error reading the packets: %s\n", pcap_geterr(handle));

debugGreen("Quit logging connection towards " << hostName);
pcap_close(handle);