본문 바로가기
코테연습

23.Who likes it?

by hxunz 2022. 4. 1.

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"

 

 

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

그냥 단순하게 문제 주어진대로 코드를 작성해보았다.

 

names의 길이가 0이라면 "no one likes this" 을 리턴하고

 

길이가 1이라면 names의 0번째 요소와 " likes this" 를 리턴하고

 

...

 

마지막으로 길이가 4이상인 경우에는 names의 앞에서 두개 요소만 리턴하고 나머지는 names의 길이에서 2를 뺀 수를 리턴하도록 하였다.

'코테연습' 카테고리의 다른 글

25.Create Phone Number  (0) 2022.04.02
24.Bit Counting  (0) 2022.04.01
22.Array.diff  (0) 2022.03.31
21.Sum of Digits / Digital Root  (0) 2022.03.31
20.Stop gninnipS My sdroW!  (0) 2022.03.30

댓글