In today's challenge, we ask that you to write a function that returns a string in which an individual's first name is swapped with their last name.
Example: nameShuffler('Emma McClane'); => "McClane Emma"
Good luck!
This challenge comes from debri on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (25)
You mean like this? It would work for your use case, although I don't know how you want to handle things like having more than 2 names or last names?
And with arrow function
Yeap, a quick, little fun one liner. I love it!
There are a few answers in JavaScript already, so let's try some things in CSS 🤩
We could separate the words into
<span>
and, using Flexbox, change the order in which they are displayed within the parent container using theorder
property. It can be easily expanded to more than 2 words, but it requires that wrapping to work.Without having to add any additional tags, we can use data-attributes to have the name and last name, and use the
::before
and::after
to display them in inverted order. It is really simple to implement but not too extendable:Also without having any additional tags, we can play with multiple text-shadows and positioning to replicate the words in inverted order. For this solution, you need to know the size of each word, and it doesn't work for more than two words... still it is a cool approach too.
You can see a demo of all of them on CodePen:
Oh damn! That box Shadow solution is pretty damn impressive!
Ruby Language
Robust version and with test specs!
output
Buffer goes buf-buf
Python version using static typing features.
Rust Playground
Just because I'm lazy
It may not work if more than 2 names are provided, but hey:
Ruby!