use crate::constants; use crate::energy::consumption::EnergyConsumption; use crate::utils::math_utils::median; pub struct ConsumptionCache { nb_vals: usize, values: Vec, } impl ConsumptionCache { pub fn new(nb_vals: usize) -> Self { Self { nb_vals, values: vec![], } } pub fn add_value(&mut self, value: EnergyConsumption) { if self.values.len() >= self.nb_vals { self.values.remove(0); } self.values.push(value); } pub fn median_value(&self) -> EnergyConsumption { if self.values.is_empty() { return constants::FALLBACK_PRODUCTION_VALUE; } median(&self.values) } } #[cfg(test)] pub mod test { use crate::constants; use crate::energy::consumption_cache::ConsumptionCache; #[test] fn empty_vec() { let cache = ConsumptionCache::new(10); assert_eq!(cache.median_value(), constants::FALLBACK_PRODUCTION_VALUE); } #[test] fn single_value() { let mut cache = ConsumptionCache::new(10); cache.add_value(-10); assert_eq!(cache.median_value(), -10); } #[test] fn four_values() { let mut cache = ConsumptionCache::new(10); cache.add_value(50); cache.add_value(-10); cache.add_value(-10); cache.add_value(-10000); assert_eq!(cache.median_value(), -10); } #[test] fn many_values() { let mut cache = ConsumptionCache::new(6); for i in 0..1000 { cache.add_value(-i); } cache.add_value(10); cache.add_value(50); cache.add_value(-10); cache.add_value(-10); cache.add_value(-30); cache.add_value(-10000); assert_eq!(cache.median_value(), -10); } }