Reverse Words Exercise

  • Code
  • Codewars
  • RegEx

It's been a really busy past couple of months, with tons of stuff going on at work. Lots of code, lots of new and difficult projects, but unfortunately none that I'm really free to post about in the blog. That said, I want to keep this thing moving along.

One of my new years resolutions for 2019 was to do 26 Code Wars exercises. I didn't get anywhere near that (and more on resolutions later), but I think I will start picking those up here and there and turn them into a little blog series.

Today's Kata comes from user jnicol and is titled Reverse Words.

Prompt

Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples "This is an example!" ==> "sihT si na !elpmaxe" "double spaces" ==> "elbuod secaps"

Solution

So this one is pretty easy, especially since at its core it's just splitting the provided string into an array, then splitting each array item (i.e., word or white space) up into its own array, then reversing, then rejoining the word, and then rejoining the whole string.

The tricky part is handling repeated white space, and to do that I need to reach for RegEx. I'm the farthest thing from a RegEx master. In real world applications I always have to do a Google search then test and break down what the expression is doing.

In this case, the RegEx is tacked on as the delimiter where the provided string will split into array items, so that in addition to making array items out of individual words, it will also break whenever there is one or more white space characters, and preserve that many white space characters as items in the split array as well.

As such it will break as follows:

const array = string.split(/(\s+)/);
string: "This    is an    example!";array: ["This", "    ", "is", " ", "an", "    ", "example!"];

Once we have that array of words and white spaces, it's simply a matter of mapping over each item in the array and reversing the characters. This was a whiteboard question I was asked in my very first technical job interview, and I completely bombed it. I was new to coding and just wasn't as practiced with string and array methods. When I got home, after sending my thank you email to the team who interviewed me, I hammered the split => reverse => join pattern into my brain. It's kind of depressing to think about messing up something that simple, but you live and you learn and you keep that knowledge in your back pocket to blog about later.

Anyway, here's the full solution. I'm sure there's a more elegant and concise way to accomplish this, and probably sometime soon I need to take a deep dive into RegEx to have a better idea about how it works, but I think this is a pretty short and easy to understand solution to the proposed problem.

function reverseWords(str) {  return str    .split(/(\s+)/)    .map((word) => word.split("").reverse().join(""))    .join("");}