코드로 우주평화

Who likes it? 본문

나는 이렇게 학습한다/Algorithm & SQL

Who likes it?

daco2020 2022. 3. 7. 20:41
반응형

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 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.

 

 

Solution:

1. Count the number of elements in the 'names' array.
2. Returns an element placed in the phrase according to the number of elements.

 

function likes(names) {
  if (names == false){
    return 'no one likes this'
  } else if (names.length > 3 ) {
    return `${names[0]}, ${names[1]} and ${names.length-2} others like this`
  } else if (names.length == 3 ) {
    return `${names[0]}, ${names[1]} and ${names[2]} like this`
  } else if (names.length == 2 ) {
    return `${names[0]} and ${names[1]} like this`
  } else if (names.length == 1 ) {
    return `${names[0]} likes this`
  }
}

 

 

Even better, you can use 'map' and 'object' to return a phrase.

function likes(names) {
  return {
    0: 'no one likes this',
    1: `${names[0]} likes this`, 
    2: `${names[0]} and ${names[1]} like this`, 
    3: `${names[0]}, ${names[1]} and ${names[2]} like this`, 
    4: `${names[0]}, ${names[1]} and ${names.length - 2} others like this`, 
  }[Math.min(4, names.length)]
}

 

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Find the middle element  (0) 2022.03.09
Highest and Lowest  (0) 2022.03.08
Abbreviate a Two Word Name  (0) 2022.03.06
Equal Sides Of An Array  (0) 2022.03.05
Is this a triangle?  (0) 2022.03.04