본문 바로가기

■ 프로그래밍/알고리즘

[JS] Who likes it?

www.codewars.com/kata/5266876b8f4bf2da9b000362/train/javascript

 

[ 문제 ]

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 :: [String] -> String, 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 be "no one likes this" 
likes ["Peter"] // must be "Peter likes this" 
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this" 
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this" 
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

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

 

 

[ 풀이 ]

2020.11.11 (5min)

function likes(names) {
  if (names.length === 0) {
    return 'no one likes this'
  } else if (names.length === 1) {
    return `${names} 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`
  }
}

 

 

'■ 프로그래밍 > 알고리즘' 카테고리의 다른 글

[JS] Stop gninnipS My sdroW!  (0) 2020.11.13
[JS] Regex validate PIN code  (0) 2020.11.12
[JS] Mumbling  (0) 2020.11.10
[JS] Is this a triangle?  (0) 2020.11.07
[JS] Isograms  (0) 2020.11.06