Решение на Форматиране на импорти от Дария Лазарова

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

Към профила на Дария Лазарова

Резултати

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

Код

pub struct Import<'a>(pub &'a [&'a str]);
#[derive(PartialEq, Clone)]
pub enum Order {
Original,
Sorted,
}
pub fn format_flat(imports: &[Import], order: Order) -> Vec<String> {
let mut result = Vec::new();
for import in imports {
let mut path = String::new();
for (i, part) in import.0.iter().enumerate() {
if i > 0 {
path.push_str("::");
}
path.push_str(part);
}
if result.contains(&path) {
continue;
}
result.push(path);
}
if order == Order::Sorted {
result.sort();
}
result
}
use std::collections::BTreeMap;
#[derive(Debug, Clone)]
struct Note {
value: Option<String>,
children: Vec<Note>,
has_self: bool,
}
impl Note {
fn new(value: Option<String>) -> Self {
Self {
value,
children: Vec::new(),
has_self: false,
}
}
fn add_path(&mut self, path: &[&str]) {
if path.is_empty() {
return;
}
let first = path[0];
let rest = &path[1..];
if let Some(child) = self.children.iter_mut().find(|child| child.value.as_deref() == Some(first)) {
if rest.is_empty() {
child.has_self = true;
} else {
child.add_path(rest);
}
} else {
let mut new_child = Note::new(Some(first.to_string()));
if rest.is_empty() {
new_child.has_self = true;
} else {
new_child.add_path(rest);
}
self.children.push(new_child);
}
}
fn to_string_vec(&self, indent: usize, is_last: bool, order: &Order) -> Vec<String> {
let mut result = Vec::new();
let indentation = " ".repeat(indent);
let mut lines = Vec::new();
if self.has_self {
lines.push("self,".to_string());
}
let mut children = self.children.clone();
if order == &Order::Sorted {
children.sort_by(|a, b| a.value.cmp(&b.value));
}
for (i, child) in children.iter().enumerate() {
let is_last_child = i == children.len() - 1;
if child.children.is_empty() {
lines.push(format!("{},", child.value.as_deref().unwrap()));
} else {
let mut child_lines = child.to_string_vec(indent + 1, is_last_child, order);
child_lines[0] = format!("{}::{{", child.value.as_deref().unwrap());
lines.push(child_lines.join("\n"));
}
}
result.push(format!("{}{{", indentation));
for line in lines {
result.push(format!("{} {}", indentation, line));
}
if is_last {
result.push(format!("{}}}\n", indentation));
} else {
result.push(format!("{}}},", indentation));
}
result
}
}
pub fn format_nested(imports: &[Import], order: Order) -> Vec<String> {
let mut crate_map: Vec<(String, Note)> = Vec::new();
for import in imports {
if let Some((crate_name, path)) = import.0.split_first() {
if let Some((_, root)) = crate_map.iter_mut().find(|(name, _)| name == crate_name) {
root.add_path(path);
} else {
let mut new_note = Note::new(Some(crate_name.to_string()));
new_note.add_path(path);
crate_map.push((crate_name.to_string(), new_note));
}
}
}
if order == Order::Sorted {
crate_map.sort_by(|a, b| a.0.cmp(&b.0));
}
let mut result = Vec::<String>::new();
for (i, (crate_name, note)) in crate_map.iter().enumerate() {
let mut lines = note.to_string_vec(0, i == crate_map.len() - 1, &order);
lines[0] = format!("{}::{{", crate_name);
result.push(lines.join("\n"));
}
result
}

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

Compiling solution v0.1.0 (/tmp/d20241203-1739405-1n60lw8/solution)
warning: unused import: `std::collections::BTreeMap`
  --> src/lib.rs:32:5
   |
32 | use std::collections::BTreeMap;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

warning: `solution` (lib) generated 1 warning
    Finished test [unoptimized + debuginfo] target(s) in 1.23s
     Running tests/solution_test.rs (target/debug/deps/solution_test-1428e1090729d165)

running 20 tests
test solution_test::test_flat_empty ... ok
test solution_test::test_flat_multi_crate ... ok
test solution_test::test_flat_original ... ok
test solution_test::test_flat_original_duplicates ... ok
test solution_test::test_flat_sorted ... ok
test solution_test::test_flat_sorted_duplicates ... ok
test solution_test::test_nested_basic ... ok
test solution_test::test_nested_deep ... FAILED
test solution_test::test_nested_empty ... ok
test solution_test::test_nested_only_crate ... FAILED
test solution_test::test_nested_original ... ok
test solution_test::test_nested_original_2 ... FAILED
test solution_test::test_nested_original_duplicates ... ok
test solution_test::test_nested_original_multi_crate ... FAILED
test solution_test::test_nested_sorted ... ok
test solution_test::test_nested_original_self ... ok
test solution_test::test_nested_sorted_duplicates ... ok
test solution_test::test_nested_sorted_2 ... FAILED
test solution_test::test_nested_sorted_self ... ok
test solution_test::test_nested_sorted_multi_crate ... FAILED

failures:

---- solution_test::test_nested_deep stdout ----
thread 'solution_test::test_nested_deep' panicked at 'assertion failed: `(left == right)`
  left: `["std::{\n    a::{\n        b::{\n            c::{\n                d,\n            }\n\n        }\n\n    }\n\n}\n"]`,
 right: `["std::{\n    a::{\n        b::{\n            c::{\n                d,\n            },\n        },\n    },\n}\n"]`', tests/solution_test.rs:160:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- solution_test::test_nested_only_crate stdout ----
thread 'solution_test::test_nested_only_crate' panicked at 'assertion failed: `(left == right)`
  left: `["my_crate::{\n}\n"]`,
 right: `["my_crate\n"]`', tests/solution_test.rs:132:5

---- solution_test::test_nested_original_2 stdout ----
thread 'solution_test::test_nested_original_2' panicked at 'assertion failed: `(left == right)`
  left: `["my_crate::{\n    c,\n    b::{\n        B2,\n        B1,\n    },\n    a::{\n        inner::{\n            I1,\n        },\n        A1,\n    }\n\n}\n"]`,
 right: `["my_crate::{\n    c,\n    b::{\n        B2,\n        B1,\n    },\n    a::{\n        inner::{\n            I1,\n        },\n        A1,\n    },\n}\n"]`', tests/solution_test.rs:198:5

---- solution_test::test_nested_original_multi_crate stdout ----
thread 'solution_test::test_nested_original_multi_crate' panicked at 'assertion failed: `(left == right)`
  left: `["crate::{\n    b,\n    a,\n},", "std::{\n    string::{\n        String,\n    }\n\n}\n"]`,
 right: `["crate::{\n    b,\n    a,\n}\n", "std::{\n    string::{\n        String,\n    },\n}\n"]`', tests/solution_test.rs:385:5

---- solution_test::test_nested_sorted_2 stdout ----
thread 'solution_test::test_nested_sorted_2' panicked at 'assertion failed: `(left == right)`
  left: `["my_crate::{\n    a::{\n        A1,\n        inner::{\n            I1,\n        }\n\n    },\n    b::{\n        B1,\n        B2,\n    },\n    c,\n}\n"]`,
 right: `["my_crate::{\n    a::{\n        A1,\n        inner::{\n            I1,\n        },\n    },\n    b::{\n        B1,\n        B2,\n    },\n    c,\n}\n"]`', tests/solution_test.rs:252:5

---- solution_test::test_nested_sorted_multi_crate stdout ----
thread 'solution_test::test_nested_sorted_multi_crate' panicked at 'assertion failed: `(left == right)`
  left: `["crate::{\n    a,\n    b,\n},", "std::{\n    string::{\n        String,\n    }\n\n}\n"]`,
 right: `["crate::{\n    a,\n    b,\n}\n", "std::{\n    string::{\n        String,\n    },\n}\n"]`', tests/solution_test.rs:414:5


failures:
    solution_test::test_nested_deep
    solution_test::test_nested_only_crate
    solution_test::test_nested_original_2
    solution_test::test_nested_original_multi_crate
    solution_test::test_nested_sorted_2
    solution_test::test_nested_sorted_multi_crate

test result: FAILED. 14 passed; 6 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

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

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

Дария качи първо решение на 03.12.2024 03:38 (преди 9 месеца)