Search code examples
javascriptrefactoringfacebook-like

refactoring/making the code better in javascript


im currently a complete noob at programming ,but i'm taking courses and about to start a bootcamp, at the moment im doing challenges in Codewars, one of the challenges was to create a function that would simulate the facebook like system.

function likes(names) {
    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 >= 4){
      return `${names[0]}, ${names[1]} and ${names.length-2} others like this`;
    } else if (names.length === 0){
      return `no one likes this`;
    } 
    else{
      return `${names} likes this`
    }
}

I tried the code and it works and passed everything but i was wondering if there was any other way more "pro" or better to refactor this code. Thanks in advance!


Solution

  • Yes, you should use switch statement here. Chaining so many else if's is considered bad practice.

    You can read about switch statement here. https://www.w3schools.com/js/js_switch.asp

    Code would look something like:

    function likes(names) {
        if(names.length<0) {
             return `${names} likes this`; //return early if possible
        }
        let answer = '';
            switch (names.length) {
              case 0:
                answer = `no one likes this`;
                break;
              case 2:          
                answer = `${names[0]} and ${names[1]} like this`;
                break;
              case 3:
                answer = `${names[0]}, ${names[1]} and ${names[2]} like this`;
                break;
              case 4:
              default:
                answer = `${names[0]}, ${names[1]} and ${names.length-2} others like this`;      
            }
        
        return answer;
    }