sunday_slate/scoring/
mod.rs1pub mod service;
2
3pub fn winning_score(points: impl IntoIterator<Item = f64>) -> Option<f64> {
7 points.into_iter().reduce(f64::max).filter(|top| *top > 0.0)
8}
9
10pub fn ties(a: f64, b: f64) -> bool {
17 hundredths(a) == hundredths(b)
18}
19
20fn hundredths(points: f64) -> i64 {
23 (points * 100.0).round() as i64
24}
25
26pub fn format_points(points: f64) -> String {
32 let hundredths = hundredths(points);
33 let sign = if hundredths < 0 { "-" } else { "" };
34 let hundredths = hundredths.unsigned_abs();
35 let whole = group_digits(&(hundredths / 100).to_string());
36 let frac = hundredths % 100;
37 format!("{sign}{whole}.{frac:02}")
38}
39
40pub fn format_thousands(v: i64) -> String {
42 let sign = if v < 0 { "-" } else { "" };
43 format!("{sign}{}", group_digits(&v.unsigned_abs().to_string()))
44}
45
46fn group_digits(digits: &str) -> String {
48 let mut out = String::new();
49 for (i, ch) in digits.char_indices() {
50 if i > 0 && (digits.len() - i).is_multiple_of(3) {
51 out.push(',');
52 }
53 out.push(ch);
54 }
55 out
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn winning_score_is_the_maximum_above_zero() {
64 assert_eq!(winning_score(vec![3.0, 17.5, 9.0]), Some(17.5));
65 assert_eq!(winning_score(vec![4.25]), Some(4.25));
66 assert_eq!(winning_score(Vec::<f64>::new()), None);
67 assert_eq!(winning_score(vec![0.0, 0.0]), None);
68 assert_eq!(winning_score(vec![-8.0, -2.0]), None);
69 }
70
71 #[test]
72 fn format_points_groups_signs_and_rounds() {
73 assert_eq!(format_points(1247.5), "1,247.50");
74 assert_eq!(format_points(-3.2), "-3.20");
75 assert_eq!(format_points(9.999), "10.00");
76 assert_eq!(format_points(1234567.0), "1,234,567.00");
77 }
78
79 #[test]
80 fn format_thousands_groups_and_signs() {
81 assert_eq!(format_thousands(700), "700");
82 assert_eq!(format_thousands(5700), "5,700");
83 assert_eq!(format_thousands(-1234567), "-1,234,567");
84 }
85
86 #[test]
87 fn two_scores_tie_exactly_when_they_display_the_same() {
88 for (a, b) in [(122.26, 122.26 + 1e-12), (9.999, 10.0), (0.0, -0.001)] {
91 assert_eq!(ties(a, b), format_points(a) == format_points(b), "{a} {b}");
92 }
93 }
94
95 #[test]
96 fn ties_ignores_differences_below_display_precision() {
97 assert!(ties(122.26, 122.26 + 1e-12));
99 assert!(ties(0.0, 0.0));
100 assert!(!ties(122.26, 122.27));
101 assert!(!ties(10.0, 90.0));
102 }
103}