DAY24:Who likes it?


Posted by birdbirdmurmur on 2023-08-06

題目連結

https://www.codewars.com/kata/5266876b8f4bf2da9b000362

解法

  • 暴力解法
    function likes(names) {
    if ( names.length === 0){
      return 'no one likes this'
    }else if ( names.length === 1){
      return `${names[0]} likes this`
    }else if ( names.length === 2){
      return `${names[0]} and ${names[1]} like this`
    }else if ( names.length === 3){
      return `${names[0]}, ${names[1]} and ${names[2]} like this`
    }else if ( names.length > 3){
      return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`
    }
    }
    
  • 轉換成switch
    function likes(names) {
    switch (names.length) {
      case 0:
        return 'no one likes this'
      case 1:
        return `${names[0]} likes this`
      case 2:
        return `${names[0]} and ${names[1]} like this`
      case 3:
        return `${names[0]}, ${names[1]} and ${names[2]} like this`
      default:
        return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`
    }
    }
    
    ### 筆記
    因為有多種不同的結果
    先使用了暴力解法後
    發現也可以使用switch
    這樣在閱讀上更易讀一些

#javascript #Codewars #switch







Related Posts

[C#] Asp.net Mvc 使用 AntiForgery

[C#] Asp.net Mvc 使用 AntiForgery

不要動!把表單交出來(1) - formData

不要動!把表單交出來(1) - formData

[Docker] Docker Volume

[Docker] Docker Volume


Comments