DEV Community staff staff

Posted on

Daily Challenge #37 - Name Swap

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 with your suggestions!

Top comments (25)

deleteman123 profile image
Fernando Doglio

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?

function nameShuffler(name) {
  return name.split(" ").reverse().join(" ")
Enter fullscreen mode Exit fullscreen mode
jmulans profile image
Ju ๐Ÿ”—

And with arrow function

const nameShuffler = string => string.split(' ').reverse().join(' ')
deleteman123 profile image
Fernando Doglio

Yeap, a quick, little fun one liner. I love it!

alvaromontoro profile image
Alvaro Montoro • Edited

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 the order property. It can be easily expanded to more than 2 words, but it requires that wrapping to work.

div {
  display: inline-flex;

div > span {
  margin-right: 1ch;

div span:nth-child(1) { order: 2; }
div span:nth-child(2) { order: 1; }

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:

<div data-first="Name" data-last="Surname"></div>

div::before {
  content: attr(data-last) ' ';

div::after {
  content: attr(data-first);

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.

<div>Name Surname</div>

div {
  box-sizing: border-box;
  display: inline-block;
  font-family: monospace;
  font-size: 1rem;
  height: 1rem;
  overflow: hidden;
  padding-top: 1rem;
  text-shadow: -5ch -1rem, 8ch -1rem;

You can see a demo of all of them on CodePen:

coreyja profile image
Corey Alexander

Oh damn! That box Shadow solution is pretty damn impressive!

mwlang profile image
Michael Lang • Edited

Ruby Language

Robust version and with test specs!

def name_shuffler name
  name.to_s.strip.split(/\s+/).reverse.join(" ")

require "spec"

describe "#name_shuffler" do
  it { expect(name_shuffler "Foo Bar").to eq "Bar Foo"}
  it { expect(name_shuffler "Foo    Bar").to eq "Bar Foo"}
  it { expect(name_shuffler "   Foo Bar").to eq "Bar Foo"}
  it { expect(name_shuffler "Foo Bar   ").to eq "Bar Foo"}
  it { expect(name_shuffler "Foo").to eq "Foo"}
  it { expect(name_shuffler "   Foo").to eq "Foo"}
  it { expect(name_shuffler "Foo   ").to eq "Foo"}
  it { expect(name_shuffler "").to eq ""}
  it { expect(name_shuffler nil).to eq ""}
  it { expect(name_shuffler 777).to eq "777"}


>> rspec name_shuffler.rb

Finished in 0.0059 seconds (files took 0.15188 seconds to load)
10 examples, 0 failures
kip13 profile image
const nameShuffle = name => name.replace(/(\S+)\s(\S+)/, '$2 $1')
tcostam profile image
๐šƒ๐š’๐šŠ๐š๐š˜ ๐™ฒ๐š˜๐šœ๐š๐šŠ
def nameShuffler(fullname: str) -> str:
    return ' '.join(fullname.split()[::-1])
tcostam profile image
๐šƒ๐š’๐šŠ๐š๐š˜ ๐™ฒ๐š˜๐šœ๐š๐šŠ

Python version using static typing features.

jay profile image

Rust Playground

fn name_shuffler(name: &str) -> String {
    name.split_whitespace().rev().collect::<Vec<&str>>().join(" ")
qm3ster profile image
Mihail Malo

Buffer goes buf-buf

const rename = name => {
    const inBuf = Buffer.from(name, 'utf8')
    const len = inBuf.length
    const outBuf = Buffer.alloc(len, 0x20)
    let prev = 0
  for (let i = 0; i < len; i++) {
    if (inBuf[i] !== 0x20) continue
    inBuf.copy(outBuf, len - i, prev, i)
    prev = i + 1
  inBuf.copy(outBuf, 0, prev)
    return outBuf.toString('utf8')
jeremy profile image
Jeremy Schuurmans


def name_shuffler(str)
  str.split(" ").reverse.join(" ")
ynndvn profile image
La blatte

It may not work if more than 2 names are provided, but hey:

const swap = (name) => {
  const [first, last] = name.split` `;
  return `${last} ${first}`;
moopet profile image
Ben Sinclair

I think I may have gone overboard with the ol' backslashes for escaping, but...

sed 's/\s*\([^ ]\+\)\s\+\([^ ]\+\)\s*/\2 \1/' <<<"  Emma McClean"
Enter fullscreen mode Exit fullscreen mode
asg5704 profile image
Alexander Garcia

Just because I'm lazy

const nameShuffler = (name) => {

  const [first, last] = [' ')]

  return `${last} ${first}`

badrecordlength profile image
Henry ๐Ÿ‘จโ€๐Ÿ’ป • Edited

Nice and simple python implementation ๐Ÿ˜

def nameShuffler(name):
    name = name.split()
mrdulin profile image


function nameShuffler(str){
  return str.split(' ').reverse().join(" ");
peter279k profile image

Here is the simple solution with Python:

def name_shuffler(string):
    string_array = string.split(' ')

    return string_array[1] + ' ' + string_array[0]
kvharish profile image

My solution in js

const nameShuffler = (name) => `${name}`.split(' ').reverse().join(' ');