Solving Codewars kata "Simple Pig Latin"

Solving Codewars kata "Simple Pig Latin"

In this article, I will be showing you how to solve a Codewars kata that I have been struggling with. I learnt of the 'map object' while solving it.

Here's the problem.

Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.

Examples:

pigIt('Pig latin is cool'); // igPay atinlay siay oolcay
pigIt('Hello world !');     // elloHay orldway !

I started by defining my string into an array and splitting the string.

const arr = str.split(" ");

Here is where it gets interesting. After studying the Mozilla documentation on the "map object", I figured I could iterate over the string while removing the first character and adding it at the end followed by the addition of the "ay".

In the code below, substr(1) helps to remove/clear the first letter of the string while the substr(0,1) helps to extract it (the string values from start index:0 to last index:1 is copied). We are sort of copy pasting the string values from where it is and placing it as the last digit.

We finally append the "ay" at the end of the string.

Here's the code snippet.

arr.map((word) => {
  return `${word.substr(1)}${word.substr(0, 1)}ay`
})

We are not out of the woods yet!! This alone will not bring into account special characters e.g. !,@,#,$ thus we use a simple method to determine if the string values are letters.

word.match(/[A-z]/i)

We will now need to bring all our code together like so.

function pigIt(str) {
  const arr = str.split(' ')
  return arr
    .map((word) => {
      return word.match(/[A-z]/i)
        ? `${word.substr(1)}${word.substr(0, 1)}ay`
        : word
    })
    .join(' ')
}

And voila! There you have it. This should pass the tests.