[ CodeWar ] - 005:用户分组

410 阅读1分钟

系列文章

题目

img-01

规则如下:

  • 空数组返回 "no one likes this"
  • 数组长度为 1,返回 "Peter likes this"
  • 数组长度为 2,返回 "Jacob and Alex like this"
  • 数组长度为 3,返回 "Max, John and Mark like this"
  • 数组长度大于 3,返回 "Alex, Jacob and 2 others like this"

解析

还是老规矩,先按照最简单直接的思路去实现功能,然后再优化。那么这道题很明显,通过判断数组长度进行不同的返回即可:

function likes(names{
  const len = names.length;
  switch (len) {
    case 0:
      return "no one likes this";
    case 1:
      return `${names[0]} likes this`;
    case 2:
      return `${names[0]} and ${names[1]} likes this`;
    case 3:
      return `${names[0]}${names[1]} and ${names[2]} like this`;
    default:
      return `${names[0]}${names[1]} and ${len - 2} others like this`;
  }
}

优化

按照上面的思路进一步优化,可以把结果放在一个 object 或者 array 中,根据数组的长度返回不同的元素即可(变种 switch):

const likes = (names) =>
  [
    "no one likes this",
    `${names[0]} likes this`,
    `${names[0]} and ${names[1]} likes this`,
    `${names[0]}${names[1]} and ${names[2]} like this`,
    `${names[0]}${names[1]} and ${names.length - 2} others like this`,
  ][Math.min(names.length, 4)];