refactoring/making javascript 中的代码更好

refactoring/making the code better in javascript

我目前是一个完全的编程新手,但我正在上课并准备开始训练营,目前我在 Codewars 中进行挑战,挑战之一是创建一个可以模拟 facebook 的功能系统.

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

我尝试了该代码并且它可以正常工作并通过了所有内容,但我想知道是否还有其他更“专业”或更好的方法来重构此代码。 提前致谢!

是的,你应该在这里使用 switch 语句。链接这么多其他 if 被认为是不好的做法。

您可以在此处阅读有关 switch 语句的信息。 https://www.w3schools.com/js/js_switch.asp

代码看起来像这样:

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

使用数组解构,你可以简化这个。

function likes(names = []) {
  if (names.length === 0) {
    return `no one likes this`;
  }
  let [first, second, third, ...rest] = names;
  if (rest.length) {
    third = `${rest.length + 1} others`;
  }
  if (third) {
    return `${first}, ${second} and ${third} like this`;
  }
  if (second) {
    return `${first} and ${second} like this`;
  }
  return `${first} likes this`;
}
console.log(likes(["name 1", "name 2", "name 3", "name 4", "name 5"]));
console.log(likes(["name 1", "name 2", "name 3"]));
console.log(likes(["name 1", "name 2"]));
console.log(likes(["name 1"]));
console.log(likes());

// name 1, name 2 and 3 others like this
// name 1, name 2 and name 3 like this
// name 1 and name 2 like this
// name 1 likes this
// no one likes this