Adding final pig latin

This commit is contained in:
2020-11-25 01:41:31 +00:00
parent 8ac081813c
commit 77daa12e47
2 changed files with 37 additions and 23 deletions

View File

@@ -1,45 +1,54 @@
// Take a &str
// - assume single words (check for no spaces)
// - convert to String
// pop the first
// append ay
// move to end
// Handle sentences: take a &str, convert to array, then do the above for each and return
// a new array
// https://scottwlaforest.com/rust/the-rust-book-chapter-8-exercises/
// NOTE: Check for vowels!
fn pig_latin(string: &str) -> String {
pub fn pig_latin(string: &str) -> String {
let s = String::from(string);
let mut portion = String::new();
let mut latinised = String::new();
let vowels = ['a', 'e', 'i', 'o', 'u'];
let mut starts_with_vowel = false;
let vowels = ['a', 'e', 'i', 'o', 'u'];
if s.is_empty() {
return s;
}
let first_character = s.chars().next().unwrap();
if vowels.contains(&first_character) {
latinised = format!("{}-hay", &s);
portion.push_str("-hay");
starts_with_vowel = true;
} else {
latinised = format!("-{}ay", &first_character);
portion = format!("-{}ay", &first_character);
}
for (pos, char) in s.char_indices() {
if pos == 0 && starts_with_vowel {
continue
} else {
if pos == 0 && !starts_with_vowel {
continue;
}
latinised.push(char);
}
latinised.push_str(&portion);
latinised
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_pig_latin() {
let string = "arust";
fn test_pig_latin_start_with_vowel() {
let string = "apple";
let result = pig_latin(string);
println!("{}", result);
assert_eq!(result, "apple-hay");
}
#[test]
fn test_pig_latin_start_with_consonant() {
let string = "first";
let result = pig_latin(string);
assert_eq!(result, "irst-fay");
}
#[test]
fn test_pig_latin_empty_string() {
let string = "";
let result = pig_latin(string);
assert_eq!(result, string)
}
}