Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

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 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"
  Note: For 4 or more names, the number in "and 2 others" simply increases.
*/

function likes(names) {
  let likeText = ["this"], arrLength = names.length
  
  if(arrLength <= 0) likeText.unshift("no one likes")
  else if(arrLength <= 1) likeText.unshift(`${names} likes`)
  else if(arrLength <= 3) likeText.unshift(names.slice(0, -1).join(", "), `and ${names[arrLength - 1]} like`)
  else likeText.unshift(names.slice(0, 2).join(", "), `and ${arrLength - 2} others like`)

  return likeText.join(' ').toString()
}

// With love @kouqhar
Source by www.codewars.com #
 
PREVIOUS NEXT
Tagged: #Who #likes
ADD COMMENT
Topic
Name
4+3 =