6kyu Who likes it

Posted tong24

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了6kyu 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"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
For more than 4 names, the number in and 2 others simply increases.

 

答案:

    // 1

              function likes (names) {

                     names = names || [];

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

                     }

              }

 

              // 2

              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;

                     });

              }

以上是关于6kyu Who likes it的主要内容,如果未能解决你的问题,请参考以下文章

6kyu Persistent Bugger

6kyu Vasya - Clerk

6kyu Unary function chainer

6kyu Equal Sides Of An Array

6kyu Decode the Morse code

如何按postgres数组中的多个ID分组