DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #266 - Who Likes It?

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 these 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.

Good luck!


This challenge comes from BattleRattle on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (24)

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"
]
Collapse
 
peter279k profile image
peter279k

Here is the code snippets with PHP:

function likes( $names ) {
    $namesCount = count($names);
    if ($namesCount === 0) {
        return "no one likes this";
    }

    if ($namesCount === 1) {
        return sprintf("%s likes this", $names[0]);
    }

    if ($namesCount === 2) {
        return sprintf("%s and %s like this", $names[0], $names[1]);
    }

    if ($namesCount === 3) {
        return sprintf("%s, %s and %s like this", $names[0], $names[1], $names[2]);
    }

    if ($namesCount >= 4) {
        $likesStringFormat = "%s, %s and %d others like this";

        $otherNamesCount = $namesCount - 2;

        return sprintf($likesStringFormat, $names[0], $names[1], $otherNamesCount);
    }
}
Collapse
 
jpantunes profile image
JP Antunes • Edited

I think you don't need the break after the return, it would be unreachable.

const 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`;
    }
}
Collapse
 
dry profile image
Hayden Mankin
let likes = ([a, b, ...c]) => c.length > 1 ? `${a}, ${b} and ${c.length} others like this` : c.length ? `${a}, ${b} and ${c[0]} like this` : b ? `${a} and ${b} like this` : a ? `${a} likes this` : `no one likes this`;

console.log(likes([])); // no one likes this
console.log(likes(["Peter"])); // Peter likes this
console.log(likes(["Jacob", "Alex"])); // Jacob and Alex like this
console.log(likes(["Max", "John", "Mark"])); // Max, John and Mark like this
console.log(likes(["Alex", "Jacob", "Mark", "Max"])); // Alex, Jacob and 2 others like this
Collapse
 
aminnairi profile image
Amin • Edited

TypeScript

const likes = ([a, b, c, ...xs]: string[]): string =>
    a === undefined
        ? "No one likes this."
        : b === undefined
            ? `${a} likes this.`
            :  c === undefined
                ? `${a} and ${b} like this.`
                : xs.length === 0
                    ? `${a}, ${b} and ${c} like this.`
                    : `${a}, ${b} and ${[c, ...xs].length} others like this.`;
Collapse
 
sam_ferree profile image
Sam Ferree

C# switch expressions to the rescue!

public static class Format
{
  public static string LikeText(string[] names) => names.Length switch
  {
    0 => "no one likes this",
    1 => $"{names[0]} likes this",
    2 => $"{names[0]} and {names[1}} like this",
    3 => $"{names[0]}, {names[1]}, and {names[2]} like this",
    _ => $"{names[0]}, {names[1]}, and {names.Length-2} others  like this",
  };
}
Collapse
 
astagi profile image
Andrea Stagi • Edited

For Python


def who_likes_this(names: list) -> str:
    who = 'no one'
    number_of_likes = len(names)
    if number_of_likes > 0 and number_of_likes < 3 :
        who = ' and '.join(names)
    elif number_of_likes >= 3:
        who = ', '.join(names[:2])
        who += ' and ' + (names[2] if number_of_likes == 3 else f' and {len(names[2:])} others')
    return f'{who} like{"" if number_of_likes > 1 else "s" } this'

Test it:

print (who_likes_this([]))
print (who_likes_this(["Peter"]))
print (who_likes_this(["Jacob", "Alex"]))
print (who_likes_this(["Max", "John", "Mark"]))
print (who_likes_this(["Alex", "Jacob", "Mark", "Max"]))
print (who_likes_this(["Alex", "Jacob", "Mark", "Max", "Peter"]))
Collapse
 
rafaacioly profile image
Rafael Acioly • Edited

Here's my version :)

from typing import List


def likes(names: List[str]) -> str:
  messages = {
    0: 'no one likes this',
    1: '%s likes this',
    2: '%s and %s like this',
    3: '%s, %s and %s like this'
  }

  message = messages.get(len(names))
  if not message:
    return '%s, %s and %d others like this' % (*names[:2], len(names) - 2)

  return message % tuple(names)
Collapse
 
cipharius profile image
Valts Liepiņš

Very declarative Haskell solution:

likes :: [String] -> String
likes []     = "no one likes this"
likes [name] = name <> " likes this"
likes names  = showMultiple names <> " like this"

showMultiple :: [String] -> String
showMultiple xs = case xs of
  []          -> ""
  [x]         -> x
  [x,x']      -> x <> " and " <> x'
  [x,x',x'']  -> x <> ", " <> showMultiple [x',x'']
  (x:x':rest) -> x <> ", " <> x' <> " and " <> (show $ length rest) <> " others"
Collapse
 
mxldevs profile image
MxL Devs • Edited

Ruby string-formatting takes an array of arguments, so if my function takes an array of names, then I just need to feed it into some pre-formatted "templates". Also the use of splat-array which I don't completely understand actually.

def likes(names)
  num_people = names.size
  case num_people
  when 0
    "no one likes this"
  when 1
    "%s likes this" %names
  when 2
    "%s and %s like this" %names
  when 3
    "%s, %s and %s like this" %names
  else
    "%s, %s and %d others like this" %[*names[0..1], num_people - 2] 
  end
end

p likes [] # must be "no one likes this"
p likes ["Peter"] # must be "Peter likes this"
p likes ["Jacob", "Alex"] # must be "Jacob and Alex like this"
p likes ["Max", "John", "Mark"] # must be "Max, John and Mark like this"
p likes ["Alex", "Jacob", "Mark", "Max"] # must be "Alex, Jacob and 2 others like this"
Collapse
 
nombrekeff profile image
Keff

Cool I did this one 3 years ago over at CodeWars, here is the answer I posted:

function likes(names) {
  switch(names.length){
    case 0:  return `no one likes this`; break;
    case 1:  return `${names[0]} likes this`; break;
    case 2:  return `${names[0]} and ${names[1]} like this`; break;
    case 3:  return `${names[0]}, ${names[1]} and ${names[2]} like this`; break;
    default: return `${names[0]}, ${names[1]} and ${names.length - 2} others like this`;
  }
}
Collapse
 
nombrekeff profile image
Keff

Looking at it now,break is not needed, as return breaks out of the switch statement.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.