6__Who_likes_it.js 1.3 KB

12345678910111213141516171819202122232425262728293031
  1. // 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.
  2. // 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:
  3. // likes [] -- must be "no one likes this"
  4. // likes ["Peter"] -- must be "Peter likes this"
  5. // likes ["Jacob", "Alex"] -- must be "Jacob and Alex like this"
  6. // likes ["Max", "John", "Mark"] -- must be "Max, John and Mark like this"
  7. // likes ["Alex", "Jacob", "Mark", "Max"] -- must be "Alex, Jacob and 2 others
  8. debugger;
  9. function likes(names) {
  10. let str = "";
  11. if (!names.length) str = "no one likes this";
  12. else {
  13. if (names.length == 1) str = names[0] + " likes this";
  14. else {
  15. if (names.length < 4) {
  16. for (i = 0; i < names.length - 1; i++) str += names[i] + ", ";
  17. str = str.slice(0, -2) + " and " + names[names.length - 1] + " like this";
  18. } else {
  19. for (i = 0; i < 2; i++) str += names[i] + ", ";
  20. str = str.slice(0, -2) + " and " + (names.length - 2) + " others like this";
  21. }
  22. }
  23. }
  24. return str;
  25. }
  26. likes(["Alex", "Jacob", "Mark", "Max"]);