6 kyu · reference

Who likes it?

StringsFundamentals

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 the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:

[]                                -->  "no one likes this"
["Peter"]                         -->  "Peter likes this"
["Jacob", "Alex"]                 -->  "Jacob and Alex like this"
["Max", "John", "Mark"]           -->  "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"]  -->  "Alex, Jacob and 2 others like this"
* return must be an allocated string
* do not mutate input

Note: For 4 or more names, the number in "and 2 others" simply increases.

Solutions

01-solution.jsView on GitHub ↗
function getSentence(names){
  if (!names.length) return 'no one';
  if (names.length <= 2) {
    return names.join(' and ');
  }
  if (names.length == 3) {
    return [names.slice(0,2).join(', '), names.slice(2,3)].join(' and ');
  }
  if (names.length > 3) {
    return [names.slice(0,2).join(', '), `${names.slice(2).length} others`].join(' and ');
  }
}

function likes(names) {
  const sentence = getSentence(names);
  const suffix = names.length >= 2 ? 'like this' : 'likes this';
  return [sentence, suffix].join(' ');
}