54 lines
1.2 KiB
Rust
54 lines
1.2 KiB
Rust
pub fn pig_latin(string: &str) -> String {
|
|
let mut portion = String::new();
|
|
let mut latinised = String::new();
|
|
let mut starts_with_vowel = false;
|
|
let vowels = ['a', 'e', 'i', 'o', 'u'];
|
|
|
|
if string.is_empty() {
|
|
return latinised;
|
|
}
|
|
|
|
let first_character = string.chars().next().unwrap();
|
|
|
|
if vowels.contains(&first_character) {
|
|
portion.push_str("-hay");
|
|
starts_with_vowel = true;
|
|
} else {
|
|
portion = format!("-{}ay", &first_character);
|
|
}
|
|
for (pos, char) in string.char_indices() {
|
|
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_start_with_vowel() {
|
|
let string = "apple";
|
|
let result = pig_latin(string);
|
|
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)
|
|
}
|
|
}
|