use std::cmp::Ordering;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SubjectRank {
pub subject: String,
pub rank: u32,
}
#[derive(Clone, Debug, PartialEq)]
pub struct FindKey {
pub match_type: u8,
pub score: f64,
pub kind: u8,
pub name: String,
pub subject: Option<SubjectRank>,
}
pub fn today_cmp(a: &FindKey, b: &FindKey) -> Ordering {
a.match_type
.cmp(&b.match_type)
.then(b.score.partial_cmp(&a.score).unwrap_or(Ordering::Equal))
.then(a.kind.cmp(&b.kind))
.then(a.name.cmp(&b.name))
}
#[derive(Clone, Debug, PartialEq)]
pub struct SortKey {
place: FindKey,
rank: u32,
own: FindKey,
}
pub fn sort_keys(results: &[FindKey]) -> Vec<SortKey> {
let group_of = |k: &FindKey| -> String {
match &k.subject {
Some(s) => format!("s:{}", s.subject),
None => format!("n:{}", k.name),
}
};
let mut best: std::collections::HashMap<String, FindKey> = Default::default();
for k in results {
let g = group_of(k);
match best.get(&g) {
Some(b) if today_cmp(b, k) != Ordering::Greater => {}
_ => {
best.insert(g, k.clone());
}
}
}
results
.iter()
.map(|k| SortKey {
place: best[&group_of(k)].clone(),
rank: k.subject.as_ref().map(|s| s.rank).unwrap_or(0),
own: k.clone(),
})
.collect()
}
pub fn cmp_sort_keys(a: &SortKey, b: &SortKey) -> Ordering {
if a.place.name == b.place.name {
a.rank.cmp(&b.rank).then_with(|| today_cmp(&a.own, &b.own))
} else {
today_cmp(&a.place, &b.place)
}
}
pub fn order(results: &[FindKey]) -> Vec<usize> {
let keys = sort_keys(results);
let mut idx: Vec<usize> = (0..results.len()).collect();
idx.sort_by(|&a, &b| cmp_sort_keys(&keys[a], &keys[b]));
idx
}