use super::{Bests, EqBests, HashBests};
use crate::Scored;
#[derive(Debug, Clone, PartialEq)]
struct Coordinate(f32);
fn sorted<K: Ord, S>(mut folded: Vec<Scored<K, S>>) -> Vec<(K, S)> {
folded.sort_by(|a, b| a.data_ref().cmp(b.data_ref()));
folded.into_iter().map(Scored::into_components).collect()
}
#[test]
fn a_second_sighting_combines_rather_than_being_dropped() {
let mut folding = HashBests::<&str, f32>::empty();
folding.fold("a", 0.5, |running, incoming| running + incoming);
folding.fold("b", 0.25, |running, incoming| running + incoming);
folding.fold("a", 0.25, |running, incoming| running + incoming);
assert_eq!(sorted(folding.drain()), vec![("a", 0.75), ("b", 0.25)]);
}
#[test]
fn the_combine_receives_running_then_incoming() {
let mut folding = HashBests::<&str, f32>::empty();
folding.fold("a", 1.0, |running, incoming| running - incoming);
folding.fold("a", 0.25, |running, incoming| running - incoming);
assert_eq!(sorted(folding.drain()), vec![("a", 0.75)]);
}
#[test]
fn the_two_mechanisms_fold_the_same_stream_alike() {
let stream = [("a", 0.5_f32), ("b", 0.25), ("a", 0.25), ("c", 0.125)];
let mut hashed = HashBests::<&str, f32>::empty();
let mut listed = EqBests::<&str, f32>::empty();
for (key, score) in stream {
hashed.fold(key, score, |running, incoming| running + incoming);
listed.fold(key, score, |running, incoming| running + incoming);
}
assert_eq!(sorted(hashed.drain()), sorted(listed.drain()));
}
#[test]
fn the_eq_row_accumulates_a_key_that_cannot_hash() {
let mut folding = EqBests::<Coordinate, f32>::empty();
folding.fold(Coordinate(1.5), 0.5, |running, incoming| running + incoming);
folding.fold(Coordinate(1.5), 0.25, |running, incoming| {
running + incoming
});
folding.fold(Coordinate(2.5), 0.125, |running, incoming| {
running + incoming
});
let folded = folding.drain();
assert_eq!(folded.len(), 2, "{folded:?}");
assert_eq!(folded[0].data_ref(), &Coordinate(1.5));
assert!((folded[0].score() - 0.75).abs() < f32::EPSILON);
}
#[test]
fn the_eq_row_keeps_first_sighting_order_across_a_repeat() {
let mut folding = EqBests::<&str, f32>::empty();
for (key, score) in [("a", 0.5_f32), ("b", 0.25), ("c", 0.125), ("a", 0.25)] {
folding.fold(key, score, |running, incoming| running + incoming);
}
let order: Vec<&str> = folding
.drain()
.into_iter()
.map(|hit| *hit.data_ref())
.collect();
assert_eq!(order, vec!["a", "b", "c"]);
}
#[test]
fn an_empty_accumulator_drains_to_nothing() {
assert!(HashBests::<&str, f32>::empty().drain().is_empty());
assert!(EqBests::<&str, f32>::empty().drain().is_empty());
}