issue #160 of rendezvous with cassidoo
Write a function that converts a sentence into Pig Latin
by Jesse Rogers
HTML
<nav class="header">
<h1>Professor Pork</h1>
</nav>
<div class="body">
<p>Enter a string and the professor will translate it into academic swine speech</p>
<textarea name="textInput" id="textInput" cols="30" rows="10"></textarea>
<div>
<button id="btn">Translate</button>
</div>
</div>
CSS
* {
box-sizing: border-box;
font-family: monospace;
}
html,
body {
margin: 0;
padding: 0;
overflow-x: hidden;
}
nav.header {
background: #212121;
color: white;
padding: 1rem;
}
.body {
padding: 1rem;
}
textarea {
display: block;
margin-bottom: 1rem;
padding: 0.5rem;
resize: vertical;
width: 100%;
}
h1 {
margin: 0;
}
button {
cursor: pointer;
padding: 0.5rem 1rem;
}
JavaScript
/**
* @author Jesse Rogers
* @fileoverview issue #160 of rendezvous with cassidoo
Write a function that converts a sentence into Pig Latin
*/
// much faster to list out vowels than consonants (:
const vowels = ['a', 'e', 'i', 'o', 'u', 'y'];
// wow so intellectual and well-read
class ScholarlyPig {
constructor() {
// local properties
this.isCapitalized = false;
this.inputString = '';
// UI refs
this.textbox = document.getElementById('textInput');
this.button = document.getElementById('btn');
// listeners
this.textbox.addEventListener('input', this.textboxHandler.bind(this));
this.button.addEventListener('click', this.submissionHandler.bind(this));
}
/**
* @param input: string
* @return: string
*/
translateWord(input) {
// typecheck input first
if (typeof input !== 'string') {
const typeError = new TypeError('Expected string for [input] but received ' + typeof input);
console.error(typeError);
throw typeError;
}
// validate input (is there any?)
if (!input || input === null) {
const invalidInputError = new Error('Invalid input: null exception');
console.error(invalidInputError);
throw invalidInputError;
}
// if string is less than three letters ignore it
if (input.length <= 2) {
return input;
}
// special case for the word "the"
if (input.toLowerCase() === 'the') {
return input;
}
// check word capitalization and set local flag before formatting later
// if first letter of word is capitalized and then later moved, we need to know
// to capitalize the *new* first letter
this.isCapitalized = this.checkCapitalization(input);
// store consonants from beginning of word here
let consonants = '';
// need access to consonant indexes outside of loop
let i;
// bop it
for (i = 0; i < input.length; i++) {
const letter = input[i].toLowerCase();
// run loop until we...