Решение на Code Identifier от Гергана Грудева

Обратно към всички решения

Към профила на Гергана Грудева

Резултати

  • 19 точки от тестове
  • 0 бонус точки
  • 19 точки общо
  • 14 успешни тест(а)
  • 1 неуспешни тест(а)

Код

#[derive(Debug)]
pub struct CodeIdentifier {
words : Vec<String>
}
impl CodeIdentifier {
pub fn new(identifier: &str) -> Option<Self> {
let id = identifier.trim().to_lowercase();
let mut copy = Vec::new();
for word in id.split("_") {
copy.push(String::from(word));
}
if Self::is_valid(copy) {
let mut res = Vec::new();
for word in id.split("_") {
res.push(String::from(word));
}
Some(CodeIdentifier {words: res})
}
else {
None
}
}
pub fn camelcase(&self) -> String {
let mut res : Vec<String> = Vec::new();
let mut copy = self.words.to_vec();
copy.remove(0);
let first : String = self.words.to_vec().remove(0);
res.push(first);
for word in copy {
res.push(String::from(Self::capitalize(&word)));
}
res.join("")
}

Копирането и местенето напред-назад са малко трудни за проследяване, и донякъде ненужни. Вместо да създадеш нов вектор само за първия елемент, може да пробваш нещо такова:

pub fn camelcase(&self) -> String {
    let mut res = Vec::new();
    let mut words = self.words.iter();

    if let Some(first_part) = words.next() {
        res.push(first_part.clone());
        for word in words {
            res.push(Self::capitalize(&word));
        }
    }

    res.join("")
}
pub fn titlecase(&self) -> String {
let mut res = Vec::new();
for word in self.words.to_vec() {
res.push(String::from(Self::capitalize(&word)));
}
res.join("")
}
pub fn kebabcase(&self) -> String {
let mut res = Vec::new();
for word in self.words.to_vec() {
res.push(String::from(word));
}
res.join("-")
}
pub fn underscore(&self) -> String {
let mut res = Vec::new();
for word in self.words.to_vec() {
res.push(String::from(word));
}
res.join("_")
}
pub fn screaming_snakecase(&self) -> String {
let mut res = Vec::new();
for word in self.words.to_vec() {
res.push(String::from(word.to_uppercase()));
}
res.join("_")
}
fn is_valid(mut words : Vec<String>) -> bool {
let first : String = words.remove(0).to_string();
let first_letter = first.chars().next().unwrap();
if !first_letter.is_alphabetic() {
return false;
}
for word in words {
if !Self::is_word(&word) {
return false;
}
}
true
}
fn is_word(s : &str) -> bool {
for ch in s.chars() {
if !ch.is_alphabetic() && !ch.is_numeric() && ch != '_' {
return false;
}
}
true
}
fn capitalize(s : &str) -> String {
let mut c = s.chars();
match c.next() {
Some(f) => f.to_uppercase().chain(c).collect(),
None => String::new()
}
}
}

Лог от изпълнението

Compiling solution v0.1.0 (/tmp/d20190123-22631-1php60b/solution)
    Finished dev [unoptimized + debuginfo] target(s) in 5.15s
     Running target/debug/deps/solution-2e785d603b538f71

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-29808948fb50ed3a

running 15 tests
test solution_test::test_both_static_and_dynamic_strings ... ok
test solution_test::test_camelcase_basic ... ok
test solution_test::test_cyrillic1 ... ok
test solution_test::test_digits1 ... ok
test solution_test::test_digits2 ... ok
test solution_test::test_digits3 ... ok
test solution_test::test_kebabcase_basic ... ok
test solution_test::test_multibyte_uppercase ... ok
test solution_test::test_normalize_case1 ... ok
test solution_test::test_normalize_case2 ... ok
test solution_test::test_screaming_snakecase_basic ... ok
test solution_test::test_titlecase_basic ... ok
test solution_test::test_underscore_basic ... ok
test solution_test::test_validity ... FAILED
test solution_test::test_whitespace ... ok

failures:

---- solution_test::test_validity stdout ----
thread 'solution_test::test_validity' panicked at 'assertion failed: CodeIdentifier::new("some-var").is_none()', tests/solution_test.rs:9:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.


failures:
    solution_test::test_validity

test result: FAILED. 14 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

error: test failed, to rerun pass '--test solution_test'

История (1 версия и 2 коментара)

Гергана качи първо решение на 25.10.2018 08:59 (преди почти 7 години)