Daily Challenge #37 - Name Swap

twitter logo ・1 min read

Daily Challenge (48 Part Series)

1) Daily Challenge #1 - String Peeler 2) Daily Challenge #2 - String Diamond 3 ... 46 3) Daily Challenge #3 - Vowel Counter 4) Daily Challenge #4 - Checkbook Balancing 5) Daily Challenge #5 - Ten Minute Walk 6) Daily Challenge #6 - Grandma and her friends 7) Daily Challenge #7 - Factorial Decomposition 8) Daily Challenge #8 - Scrabble Word Calculator 9) Daily Challenge #9 - What's Your Number? 10) Daily Challenge #10 - Calculator 11) Daily Challenge #11 - Cubic Numbers 12) Daily Challenge #12 - Next Larger Number 13) Daily Challenge #13 - Twice Linear 14) Daily Challenge #14 - Square into Squares 15) Daily Challenge #15 - Stop gninnipS My sdroW! 16) Daily Challenge #16 - Number of People on the Bus 17) Daily Challenge #17 - Double Trouble 18) Daily Challenge #18 - Triple Trouble 19) Daily Challenge #19 - Turn numbers into words 20) Daily Challenge Post #20 - Number Check 21) Daily Challenge #21 - Human Readable Time 22) Daily Challenge #22 - Simple Pig Latin 23) Daily Challenge #23 - Morse Code Decoder 24) Daily Challenge #24 - Shortest Step 25) Daily Challenge #25 - Double Cola 26) Daily Challenge #26 - Ranking Position 27) Daily Challenge #27 - Unlucky Days 28) Daily Challenge #28 - Kill the Monster! 29) Daily Challenge #29 - Xs and Os 30) Daily Challenge #30 - What is the price? 31) Daily Challenge #31 - Count IPv4 Addresses 32) Daily Challenge #32 - Hide Phone Numbers 33) Daily Challenge #33 - Did you mean...? 34) Daily Challenge #34 - WeIrD StRiNg CaSe 35) Daily Challenge #35 - Find the Outlier 36) Daily Challenge #36 - Let's go for a run! 37) Daily Challenge #37 - Name Swap 38) Daily Challenge #38 - Middle Name 39) Daily Challenge #39 - Virus 40) Daily Challenge #40 - Counting Sheep 41) Daily Challenge #41 - Greed is Good 42) Daily Challenge #42 - Caesar Cipher 43) Daily Challenge #43 - Boardgame Fight Resolver 44) Daily Challenge #44 - Mexican Wave 45) Daily Challenge #45 - Change Machine 46) Daily Challenge #46 - ??? 47) Daily Challenge #47 - Alphabets 48) Daily Challenge #48 - Facebook Likes

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!

twitter logo DISCUSS (22)
markdown guide
 

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(" ")
}
 

And with arrow function

const nameShuffler = string => string.split(' ').reverse().join(' ')
 
 

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:

 

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

 

Ruby Language

Robust version and with test specs!

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

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"}
end

output

>> rspec name_shuffler.rb
..........

Finished in 0.0059 seconds (files took 0.15188 seconds to load)
10 examples, 0 failures
 

Rust Playground

fn name_shuffler(name: &str) -> String {
    name.split_whitespace().rev().collect::<Vec<&str>>().join(" ")
}
 
 
const nameShuffle = name => name.replace(/(\S+)\s(\S+)/, '$2 $1')
 

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')
}
 

Just because I'm lazy

const nameShuffler = (name) => {

  const [first, last] = [...name.split(' ')]

  return `${last} ${first}`

}
 

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

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

Ruby!

def name_shuffler(str)
  str.split(" ").reverse.join(" ")
end
 
 

Nice and simple python implementation 😁

def nameShuffler(name):
    name = name.split()
    name.reverse()
    print(str(name))
 

ruby 2.7

def nameShuffler(s)
  s |> split ' ', 2 |> then { "#@2 #@1" }
end
p nameShuffler('Emma McClane')
 

probably a terrible practice but that's how I'd do it

const nameShuffler = name => name.split(' ')[1] + ' ' + name.split(' ')[0]
 
nameShuffler = unwords . reverse . words

Seems pretty simple (Haskell)

 

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

sed 's/\s*\([^ ]\+\)\s\+\([^ ]\+\)\s*/\2 \1/' <<<"  Emma McClean"
 
 

Python :

def name_shuffler(name): return ' '.join([name.split()[1], name.split()[0]])
Classic DEV Post from Mar 2

What is the importance of committing mistakes?

It is a well-known fact that all human beings are different and unique in their ways. However, no matter how unique and different we are from one another, one thing which remains the same between all of us is our innate nature to commit mistakes.

dev.to staff profile image
The hardworking team behind dev.to ❀️

Let's talk shop πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Sign up (for free)