likes.js

Problem

• You probably know the ‘like’ system from Facebook.
• Facebook의 ‘like’ 시스템을 알고 있을 것이다.
• We want to create the text that should be displayed next to such an item.
• 옆에 표시할 텍스트를 작성하려고 한다.
• Implement a function, which must take in input array, containing the names of people who like an item.
• like를 누른 사람들의 이름을 포함하는 배열을 가져오는 함수를 작성한다.
• For 4 more names, the number in ‘and 2 others’ simply increases.
• 이름이 4개 이상인 경우, ‘and 2 others’와 같이 단순히 증가시킨다.

For example

likes([]) => `no one likes this`

likes([‘Sam’]) => `Sam likes this`

likes([‘Ralph’, ‘Lauren’]) => `Ralph and Lauren like this`

likes([‘Ralph’, ‘Lauren’, ‘Leo’]) => `Ralph, Lauren and Leo like this`

likes([‘Sam’, ‘Ralph’, ‘Lauren’, ‘Leo’]) => `Sam, Ralph and 2 others like this`

Solution 01

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

likes([]);                                 // no one likes this
likes(['Sam']);                            // Sam likes this
likes(['Ralph', 'Lauren']);                // Ralph and Lauren like this
likes(['Ralph', 'Lauren', 'Leo']);         // Ralph, Lauren and Leo like this
likes(['Sam', 'Ralph', 'Lauren', 'Leo']);  // Sam, Ralph and 2 others like this
``````

Solution 02

``````function likes(arr) {
switch(arr.length) {
case 0:
return 'no one likes this';
case 1:
return `\${arr[0]} likes this`;
case 2:
return `\${arr[0]} and \${arr[1]} like this`;
case 3:
return `\${arr[0]}, \${arr[1]} and \${arr[2]} like this`;
default:
return `\${arr[0]}, \${arr[1]} and \${arr.length - 2} others like this`;
}
}

likes([]);                                 // no one likes this
likes(['Sam']);                            // Sam likes this
likes(['Ralph', 'Lauren']);                // Ralph and Lauren like this
likes(['Ralph', 'Lauren', 'Leo']);         // Ralph, Lauren and Leo like this
likes(['Sam', 'Ralph', 'Lauren', 'Leo']);  // Sam, Ralph and 2 others like this
``````

Solution 03

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

likes([]);                                 // no one likes this
likes(['Sam']);                            // Sam likes this
likes(['Ralph', 'Lauren']);                // Ralph and Lauren like this
likes(['Ralph', 'Lauren', 'Leo']);         // Ralph, Lauren and Leo like this
likes(['Sam', 'Ralph', 'Lauren', 'Leo']);  // Sam, Ralph and 2 others like this
``````

© 2018. by dubbsong

` 오 많 배`