CodeWars - Who likes it?

来~

题目:

/**You probably know the “like” system from Facebook and other pages.
People can “like” blog posts, pictures or other items.
We want to create the text that should be displayed next to such an item.
Implement a function likes :: [String] -> String, which must take in input array,
containing the names of people who like an item.
It must return the display text as shown in the examples:
likes [] // must be “no one likes this”
空数组的时候 输出no one + likes this
likes [“Peter”] // must be “Peter likes this”
一个数据的时候就 人名 + likes this
likes [“Jacob”, “Alex”] // must be “Jacob and Alex like this”
两个数据的时候 one and two like this
likes [“Max”, “John”, “Mark”] // must be “Max, John and Mark like this”
三个数据的时候 one,two and three like this
likes [“Alex”, “Jaco”, “Mark”, “Max”] // must be “Alex, Jacob and 2 others like this”
四个数据 one,two and
names 是一个数组
*/

代码

function likes(names) {
  // TODO
  while(names.length){
    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 {
        return names[0]+', '+names[1]+" and "+(names.length-2)+" others like this";
    }
  }
  return "no one likes this";
}

也可以用switch 进行

function likes(names) {
  names = names || [];    //没有内容的时候 就给长度为0
  switch(names.length){
    case 0: return 'no one likes this'; break;
    case 1: return names[0] + ' likes this'; break;
    case 2: return names[0] + ' and ' + names[1] + ' like this'; break;
    case 3: return names[0] + ', ' + names[1] + ' and ' + names[2] + ' like this'; break;
    default: return names[0] + ', ' + names[1] + ' and ' + (names.length - 2) + ' others like this';
  }
}

大神的,打扰了~!正则,正则!! 正则不是一天练成的,是很多天!!!


function likes (names) {
  var templates = [
    'no one likes this',
    '{name} likes this',
    '{name} and {name} like this',
    '{name}, {name} and {name} like this',
    '{name}, {name} and {n} others like this'
  ];
  var idx = Math.min(names.length, 4);  //取最小值
  
  return templates[idx].replace(/{name}|{n}/g, function (val) {
    return val === '{name}' ? names.shift() : names.length;
  });
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值