Решение на Форматиране на импорти от Станислав Иванов

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

Към профила на Станислав Иванов

Резултати

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

Код

use std::cmp::Ordering;
use std::collections::HashSet;
pub struct Import<'a>(pub &'a [&'a str]);
pub enum Order {
Original,
Sorted,
}
impl Order {
fn ordering<T: Ord>(&self, a: &T, b: &T) -> Ordering {
match self {
Order::Original => Ordering::Equal,
Order::Sorted => a.cmp(b),
}
}
}
pub fn format_flat(imports: &[Import], order: Order) -> Vec<String> {
let mut unique_imports = HashSet::new();
let mut imports = imports
.iter()
.map(|Import(paths)| {
paths
.iter()
.map(|path| path.to_string())
.collect::<Vec<String>>()
.join("::")
})
.filter(|import| unique_imports.insert(import.clone()))
.collect::<Vec<String>>();
imports.sort_by(|a, b| order.ordering(a, b));
imports
}
#[derive(Clone)]
struct ImportsTree {
value: String,
children: Vec<ImportsTree>,
}
impl ImportsTree {
fn new(value: String) -> Self {
Self {
value,
children: Vec::new(),
}
}
fn insert(&mut self, paths: &[&str]) {
let Some(path) = paths.first() else {
return;
};
let child = self.children.iter_mut().find(|child| child.value == *path);
match child {
Some(child) => child.insert(&paths[1..]),
None => {
let mut child = ImportsTree::new(path.to_string());
child.insert(&paths[1..]);
self.children.push(child);
}
}
}
}
pub fn format_nested(imports: &[Import], order: Order) -> Vec<String> {
let mut tree = ImportsTree::new(String::new());
imports
.iter()
.map(|Import(path)| [&path[..], &["self"][..]].concat())
.for_each(|path| tree.insert(&path));
impl ImportsTree {
fn imports(&self, order: &Order) -> String {
if self.children.is_empty()
|| (self.children.len() == 1 && self.children[0].value == "self")
{
return self.value.clone();
}
let mut children = self.children.clone();
children.sort_by(|a, b| order.ordering(&a.value, &b.value));
if let Some(self_index) = children.iter().position(|child| child.value == "self") {
let self_child = children.remove(self_index);
children.insert(0, self_child);
}
let children_imports = children
.iter()
.map(|child| format!("{},", child.imports(order)))
.collect::<Vec<String>>()
.join("\n")
.replace("\n", "\n ");
format!("{}::{{\n {}\n}}", self.value, children_imports)
}
}
tree.children
.iter()
.map(|child| format!("{}\n", child.imports(&order)))
.collect()
}

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

Compiling solution v0.1.0 (/tmp/d20241203-1739405-1507vjz/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.35s
     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_duplicates ... ok
test solution_test::test_flat_original ... 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_empty ... ok
test solution_test::test_nested_deep ... ok
test solution_test::test_nested_only_crate ... ok
test solution_test::test_nested_original ... ok
test solution_test::test_nested_original_2 ... ok
test solution_test::test_nested_original_duplicates ... ok
test solution_test::test_nested_original_multi_crate ... ok
test solution_test::test_nested_original_self ... ok
test solution_test::test_nested_sorted ... ok
test solution_test::test_nested_sorted_2 ... ok
test solution_test::test_nested_sorted_duplicates ... ok
test solution_test::test_nested_sorted_multi_crate ... ok
test solution_test::test_nested_sorted_self ... ok

test result: ok. 20 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

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

Станислав качи първо решение на 29.11.2024 23:28 (преди 10 месеца)