[JS Practice] like function(类似Facebook上的一个点赞方法)

Title :
Like function(类似Facebook上的一个点赞方法)

Description:
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(), 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 return “no one likes this”
likes([‘Peter’]); // must return “Peter likes this”
likes([‘Jacob’, ‘Alex’]); // must return “Jacob and Alex like this”
likes([‘Max’, ‘John’, ‘Mark’]); // must return “Max, John and Mark like this”
likes([‘Alex’, ‘Jacob’, ‘Mark’, ‘Max’]); // must return “Alex, Jacob and 2 others like this”
For more than 4 names, the number in and 2 others simply increases.

要求实现一个likes方法,输入的是一个包含所有点赞的用户名的数组,输出的是包含这些用户名的一句text,如果用户数量小于等于三个,则全部显示在句子里,如果超过,则显示显示前两个,剩下的显示剩余用户数量。考察到javascript的基本输出语法。

My solution (with if, not prefect) :

function likes(names) {
  var arrLength = names.length;
  if(arrLength == 0) {
    return "no one likes this";
  } else if(arrLength == 1) {
    return names[0] + " likes this";
  } else if(arrLength == 2) {
    return names[0] +" and " + names[1] + " like this";
  } else if(arrLength == 3) {
    return names[0] + ", " +names[1] +" and " + names[2] + " like this";
  } else {
    var leth = arrLength-2;
    return names[0] +", " +names[1] +" and " + leth + " others like this";
  }
}

The solution with switch/case :

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

### The following functions have to be tested ###
We can also use sprintf or vsprintf to format the output, vsprintf allows us to use an array directly.

sprintf :

sprintf("%s likes this", names[0]);

vsprintf, it will takes the elements corresponds :

vsprintf("%s, %s and %s likes this", names);

Ref. from codewars

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s