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
/ol
to 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
format
function with["no one"]
, the complete input, or the two first elements followed by the remaining quantity of items. Finally, we add (or not) ans
to thelike
, and return the built string!Trying with Gwion
Thank god for template strings.
PHP