Translating Pig Latin with Flatten and Reduce

Pig Latin[5] is a silly pseudolanguage based on English. Translating an English sentence into Pig Latin is simple. Split each sentence into words and put each word through the following modifications:

  • Remove the first letter of each word: “Pig Latin” becomes “ig atin” (exception: ignore single-letter words)

  • Add the first letter removed in the previous step plus ‘ay’ to the end of the word: “ig-pay atin-lay”

Alas, nothing is ever that simple, and there’s an edge case we need to worry about: single-letter words (specifically, a and I). To keep it simple, in the event of a single-letter word, our code will let it be and return the word unchanged.

Advanced Pig Latin

images/aside-icons/note.png

Like any natural language, there are many dialects of Pig Latin. Some break things down further, checking whether the word starts with a consonant or a vowel. We’re just using a simplified Pig Latin as an example here. If you want to add more rules after you finish this section, go for it!

Pig Latin is enormous fun to say aloud. Some folks are even able to have full conversations in it without missing a beat. On the other hand, we want to write a program to do all that work for us. Translating the single-word rules to JavaScript results in this function:

 // Converts a word in English to one in Pig Latin
 function​ pigLatinify(word) {
 // Handle single-letter case and empty strings
 if​ (word.length < 2) {
 return​ word;
  }
 return​ word.slice(1) + ​'-'​ + word[0].toLowerCase() + ​'ay'​;
 }

You can use the techniques from the last chapter (fromEvent and map) to connect this function to a textbox that prints out a Pig Latin translation on every keystroke:

 let​ keyUp$ = fromEvent(textbox, ​'keyup'​)
 .pipe(
  map(event => event.target.value),
  map(wordString => wordString.split(​/​​s​​+/​)),
  map(wordArray => wordArray.map(pigLatinify))
 )
 .subscribe(translated => console.log(translated));

A quick review: Every keyup event is sent down the stream by the fromEvent constructor. The first map extracts the value of the textbox. The second splits the string using a regex that matches one or more instances of whitespace (s: match whitespace, +: one or more instances). The final map takes the array of words and passes each word through the translation function (using Array.prototype.map).

The three-map snippet works just fine, but it’s only one of many possible ways to implement a real-time translator. In the next section, you’ll see some new techniques used to the same effect, but they provide building blocks that the rest of the book will expand on. The first of these is the idea of function that flattens multidimensional collections so we can better handle that array of words.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.68