In today's challenge, you are asked to create a like system from Facebook; a text which displays the names of people who liked an item.
For example:
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"Note: For 4 or more names, the number in and 2 others simply increases.
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
This challenge comes from BattleRattle on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Top comments (34)
CSS
This is a "don't do this at home" type of solution. Will it work? Yes. Is is worth it? We can all agree that CSS is always worth it (:P), but in this case, it may end up with a ton of unnecessary HTML code.
The idea is to use a
ul/olto represent the list of people, and with counters keep track of the number of likes (aka people in the list). Then with pseudo-elements display the appropriate message or connector.And here is a demo on codepen:
Thanks to this challenge, I learnt that CSS counters don't increment in elements with
display: none. Which is nice.Also, I'm more of an Oxford-comma type of person, but the challenge didn't have it. (That is my excuse and I'll stick to it)
Bloody brilliant!
Some simple pattern matching with Haskell.
ruby <3
Nice!
I can't wait ruby 2.7 release!
JS, with each case defined. I went for straightforward, though there's probably room to condense this somehow given the repetition:
lol great minds think alike
Using destructuring with JS
Rust Playground
And a bit of golf with the Intl.ListFormat tool!
Here is the output:
Basically, with a bit of wibbly wobbly trickery, depending on the input length, we either call the
formatfunction with["no one"], the complete input, or the two first elements followed by the remaining quantity of items. Finally, we add (or not) ansto thelike, and return the built string!Late to the party and I can see people have already posted a similar solution but just going to post anyway. Sometimes keeping it simple is OK :)
My simple solution in js
PHP
At first i've used a lot of
ifstatement then i got excited and tried another pointPython version (using as fewer
ifsas possible):Possible improvements: instead of
You can write:
Or - if you want to get fancy:
Or even:
But of course - all of this is redundant, since you already check for
likes_quantity > 3. So how about this:Nice, it was in fact redundant getting the message content, thanks for sharing :D