Created
November 10, 2018 15:51
-
-
Save tvaisanen/f8df9555856a5668b2ad3b35d8b8dcfd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn component_name_to_dashed(name: &String) -> String { | |
let mut dashed:String = String::new(); | |
let camel_catcher: Regex = Regex::new(r"([A-Z][a-z]*)").unwrap(); | |
let words: Vec<&str> = camel_catcher.find_iter(name) | |
.map(|match_| match_.as_str()) | |
.collect(); | |
let word_count: usize = words.len(); | |
for (i, word) in words.iter().enumerate() { | |
dashed.push_str(&word.to_lowercase()); | |
// if the word is the last one | |
// don't add the dash '-' | |
if i+1 != word_count { | |
dashed.push('-'); | |
} | |
} | |
dashed | |
} | |
#[test] | |
fn component_name_to_dashed_works(){ | |
let camel: String = "ComponentName".to_string(); | |
let expected = "component-name".to_string(); | |
let dashed: String = component_name_to_dashed(&camel); | |
assert_eq!(expected, dashed); | |
} | |
#[test] | |
fn component_name_to_dashed_works_with_3_or_more_words(){ | |
let camel: String = "ComponentNameWithMoreWords".to_string(); | |
let expected = "component-name-with-more-words".to_string(); | |
let dashed: String = component_name_to_dashed(&camel); | |
assert_eq!(expected, dashed); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment