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

Day 23-Turtle Crossing Game

Day 23-Turtle Crossing Game

React(5) - controlled & uncontrolled component

React(5) - controlled & uncontrolled component

F2E合作社|創建表單與控制|Bootstrap 5 網頁框架開發入門

F2E合作社|創建表單與控制|Bootstrap 5 網頁框架開發入門


Comments