DEV Community

Cover image for How I REACTO To Algos: Pig Latin
A.M. Hernandez
A.M. Hernandez

Posted on • Updated on

How I REACTO To Algos: Pig Latin

How I react to algos

This is the second article in a series aiming to familiarize you with REACTO. Today we will tackle a fun one I found on Codewars to translate text to Pig Latin. 🐽

Check out the first article in the series, First Double

Remember REACTO?

REACTO is an acronym that represents the method we will use in solving this problem. As a reminder, these are the steps:

  • R: Restate
  • E: Example
  • A: Approach
  • C: Code
  • T: Test
  • O: Optimize

That's the order and we're sticking to it. Let's get started!

The Prompt

You'll be given a string of words. Create a function called toPigLatin that moves the first letter of each word in a string to the end of the word, then adds "ay" to the end of the word before returning the newly formed string. Leave punctuation marks untouched.

That, right there, is how Pig Latin is made. πŸ·πŸ’–

R: Restate the prompt

Here we are in the first step, so let's do what it recommends!

/* 
R: Restate

given a string, create function that takes each word of the
string, moves its first letter to the end and adds "ay"
before returning the string.
*/
Enter fullscreen mode Exit fullscreen mode

This time I am going to ask the imaginary instructor some clarifying questions:

Q: Should the return value preserve letter case?
A: No, the string returned should be in all lower case.

Q: Will the function receive a string with numbers in it?
A: No.

In light of this new information, the R: Restate should be modified:

/* 
R: Restate

- given a string, create function that takes each word of the string, moves its first letter to the end and adds "ay" before returning the string. 
- The return value should be in lower case.
*/
Enter fullscreen mode Exit fullscreen mode

E: Examples

You'll always get examples, but if none are supplied you can always ask! Here are some examples of inputs and their expected outputs.

/*
E: Examples

toPigLatin('Pig latin is cool.'); // igpay atinlay siay oolcay.
toPigLatin('Hello world!');     // ellohay orldway!
toPigLatin('I know this is a great place'); // iay nowkay histay siay aay reatgay lacepay
toPigLatin("We can't do this."); // eway an'tcay oday histay.
toPigLatin('Is this the way?'); // siay histay hetay ayway?
*/
Enter fullscreen mode Exit fullscreen mode

A: Approach

Now it is time to write out the approach to take before writing any actual code. Pseudocode is great here.

/*
A: Approach

- create function toPigLatin that takes a string argument
- assign letters of the alphabet to variable with all letters in lower case, call it alphabet
- declare a variable to hold the final string, initialized to empty string, call it pigStr
- split the argument string where there are spaces, " ", which will create an array of words
- iterate over this array of words
- - declare variable to hold current word in loop and make it lower case
- - check if the last character of this word is a letter (is it in the alphabet string?)
- - - if the character is not a letter:
- - - - take characters from word, skipping the first and last, and add to pigStr followed by first character, then "ay", then the last character of the word.(pig! >> ig + p + ay + ! >> igpay!)
- - - else take the word but skip the first letter and add it to pigStr followed by the first letter of the word and then "ay". (cat >> at + c + ay >> atcay)
- - at the end of every loop we should add a space, " ", to pigStr unless it is the last loop.
- return pigStr
*/
Enter fullscreen mode Exit fullscreen mode

There are many ways to get to the solution and the path I have laid out is going to be more verbose than what you might come up with if you aren't a beginner. Let's complete this challenge first and then we can tidy up. 🧹

C: Code

Time to code! πŸ§‘β€πŸ’»
If you've read the previous article in this series you'll know that I like to copy my Approach comments and paste them into my code as a guide.

// create function toPigLatin that takes a string argument
function toPigLatin() {
  // assign letters of the alphabet to variable with all letters in lower case, call it alphabet
  let alphabet = "abcdefghijklmnopqrstuvwxyz";

  // declare a variable to hold the final string, initialized to empty string, call it pigStr
  let pigStr = "";

  // split the argument string where there are spaces, " ", which will create an array of words
  let wordsArr = str.split(" ");

  // iterate over this array of words
  for (let i = 0; i < wordsArr.length; i++) {
    // declare variable to hold current word in loop and make it lower case
    let word = wordsArr[i].toLowerCase();

    // check if the last character of this word is a letter (is it in the alphabet string?)
    if (alphabet.includes(word[word.length - 1]) === false) {
      // if the character is not a letter:
      // take characters from word, skipping the first and last, and add to pigStr followed by first character, then "ay", then the last character of the word.(pig! >> ig + p + ay + ! >> igpay!)
      pigStr += word.slice(1, -1) + word[0] + "ay" + word[word.length - 1];
    } else {
      // else take the word but skip the first letter and add it to pigStr followed by the first letter of the word and then "ay". (cat >> at + c + ay >> atcay)
      pigStr += word.slice(1) + word[0] + "ay";
    }

    // at the end of every loop we should add a space, " ", to pigStr unless it is the last loop.
    if (i !== wordsArr.length - 1) {
      pigStr += " ";
    }
  }

  // return pigStr
  return pigStr;
}
Enter fullscreen mode Exit fullscreen mode

That's everything for the code! We are just going to clean up the comments now and add it to a Codepen along with some console.log statements serving as tests.
Here's the function without comments:

function toPigLatin(str) {
  let alphabet = "abcdefghijklmnopqrstuvwxyz";
  let pigStr = "";
  let wordsArr = str.split(" ");
  for (let i = 0; i < wordsArr.length; i++) {
    let word = wordsArr[i].toLowerCase();
    if (alphabet.includes(word[word.length - 1]) === false) {
      pigStr += word.slice(1, -1) + word[0] + "ay" + word[word.length - 1];
    } else {
      pigStr += word.slice(1) + word[0] + "ay";
    }
    if (i !== wordsArr.length - 1) {
      pigStr += " ";
    }
  }
  return pigStr;
}
Enter fullscreen mode Exit fullscreen mode

Now let's test this!

T: Test

Testing time! Here is a Codepen with the function in the JS tab and the results. Feel free to play around with the code and explore.

O: Optimize

We passed our own tests! πŸŽ‰ Big celebration! Now let's optimize, if possible.

function toPigLatin(str) {
  let alphabet = "abcdefghijklmnopqrstuvwxyz";
  let pigArr = str.split(" ");
  return pigArr
    .map((word) => {
      word = word.toLowerCase();
      if (alphabet.includes(word[word.length - 1]) === false) {
        return word.slice(1, -1) + word[0] + "ay" + word[word.length - 1];
      }
      return word.slice(1) + word[0] + "ay";
    })
    .join(" ");
}
Enter fullscreen mode Exit fullscreen mode

Can you tell what changes were made? Take a look and don't forget to copy and paste this into the Codepen above to see if you get the same result. Or visit the Codepen here and get to exploring! It's almost as cute as a pig! πŸ–πŸ–!

Thank You

I want to thank you for taking time out of your day to read this post. Follow me here on dev.to if you'd like to see more content like this. I post about my explorations into the world of web development. I'll see you around!

Top comments (0)