journal/journal_cli/src/formatting.rs

99 lines
2.5 KiB
Rust
Raw Normal View History

2024-11-22 17:04:18 +00:00
use journal::types::{Dose, Estimation, Experience, Ingestion, Unit};
2024-11-20 19:15:07 +00:00
pub fn format_experience_title(experience: &Experience) -> String {
format!("{}: {}", experience.title, experience.creation_time)
}
2024-11-22 17:04:18 +00:00
pub fn format_ingestion_dose(dose: Option<&Dose>, unit: &Unit) -> String {
2024-11-20 19:15:07 +00:00
match dose {
2024-11-22 17:04:18 +00:00
Some(dose) => match unit {
Unit::Simple(unit) => {
let is_estimate = dose.estimation.is_estimate();
let estimate = if is_estimate { "~" } else { "" };
let standard_deviation = {
if let Estimation::StandardDeviation(deviation) = dose.estimation {
format!("±{}", (deviation.deviation * 100.0).round() / 100.0)
} else {
"".to_string()
}
};
let unknown = if dose.contains_unknown {
"+Unknown"
2024-11-20 19:15:07 +00:00
} else {
2024-11-22 17:04:18 +00:00
""
};
let dose = (dose.value * 100.0).round() / 100.0;
format!("{estimate}{dose}{standard_deviation}{unknown} {unit}")
}
Unit::Custom { id: _id, unit } => {
let unit = unit.clone().unwrap();
let unit_unit = Unit::Simple(unit.unit.clone());
let ingestion_dose = match &unit.dose {
Some(unit_dose) => dose * unit_dose,
None => dose.clone(),
};
let ingestion_unit = Unit::Simple(unit.original_unit.clone());
let ingestion_dose = format_ingestion_dose(Some(&ingestion_dose), &ingestion_unit);
let dose_per_unit = format_ingestion_dose(unit.dose.as_ref(), &ingestion_unit);
2024-11-22 17:07:42 +00:00
let custom_unit_dose = format_ingestion_dose(Some(dose), &unit_unit);
2024-11-20 19:15:07 +00:00
2024-11-22 17:04:18 +00:00
format!("{ingestion_dose} ({dose_per_unit} * {custom_unit_dose})")
}
},
None => format!(
"Unknown {}",
match unit {
Unit::Simple(unit) => unit,
Unit::Custom { id: _id, unit } => &unit.as_ref().unwrap().original_unit,
}
),
2024-11-20 19:15:07 +00:00
}
}
pub fn format_ingestion_time(ingestion: &Ingestion) -> String {
ingestion.ingestion_time.format("%a %I:%M %p").to_string()
}
2024-11-22 17:04:18 +00:00
pub fn format_ingestion_roa(ingestion: &Ingestion, unit: &Unit) -> String {
if let Unit::Custom { id: _id, unit } = unit {
format!("{:?} ({})", ingestion.roa, &unit.as_ref().unwrap().name)
2024-11-20 19:15:07 +00:00
} else {
format!("{:?}", ingestion.roa)
}
}
2024-11-22 17:04:18 +00:00
#[cfg(test)]
mod tests {
use journal::types::CustomUnit;
use super::*;
#[test]
fn format_unknown_dose() {
let result = format_ingestion_dose(None, &Unit::Simple("mg".to_string()));
assert_eq!(result, "Unknown mg");
}
#[test]
fn format_unknown_dose_custom_unit() {
let result = format_ingestion_dose(
None,
&Unit::Custom {
id: 0,
unit: Some(CustomUnit {
original_unit: "mg".to_string(),
..CustomUnit::default()
}),
},
);
assert_eq!(result, "Unknown mg");
}
}