Stuck on implementing: For 4 or more names, the number in "and 2 others" simply increases.
The following was from a codewars kata. In order to implement the Note (highlighted below) I had to look at other solutions.
Kata:
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.
default:
return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`;
Breakdown:
When there are more than three people who like the item, the function only includes the names of the first two people who like the item, followed by the string "and", and then the number of additional people who like the item. By subtracting two from the length of the names
array, we get the number of additional people who like the item.
For example, if the names
array has a length of 5, then there are three additional people who like the item (i.e., 5 - 2 = 3), so the string literal would be "John, Sarah and 3 others like this"
.
This approach is used because listing the names of all the people who like the item might become unwieldy if there are many names. By only listing the first two names and indicating the number of additional people, the function can provide a concise and informative message about who likes the item.