DEV Community

Discussion on: Daily Challenge #266 - Who Likes It?

Collapse
 
willsmart profile image
willsmart

This'd be a good use for template literals. Here's a quicky in javascript:

function likesStringForNames(names) {
  const [first, second, third] = names;
  switch (names.length) {
    case 0: return "no one likes this";
    case 1: return `${first} likes this`;
    case 2: return `${first} and ${second} like this`;
    case 3: return `${first}, ${second} and ${third} like this`;
    default: return `${first}, ${second} and ${names.length - 2} others like this`;
  }
}

Sanity check:

[
  [],
  ["Peter"],
  ["Jacob", "Alex"],
  ["Max", "John", "Mark"],
  ["Alex", "Jacob", "Mark", "Max"],
  ["Alex", "Mark", ...Array(10000)]
].map(likesStringForNames)
-->
[
  "no one likes this",
  "Peter likes this",
  "Jacob and Alex like this",
  "Max, John and Mark like this",
  "Alex, Jacob and 2 others like this",
  "Alex, Mark and 10000 others like this"
]