oxihuman_core/
strategy_pattern.rs1#![allow(dead_code)]
4
5pub struct SortStrategy {
6 pub name: String,
7 pub ascending: bool,
8}
9
10pub fn new_sort_strategy(name: &str, ascending: bool) -> SortStrategy {
11 SortStrategy {
12 name: name.to_string(),
13 ascending,
14 }
15}
16
17pub fn sort_apply_f32(s: &SortStrategy, data: &mut [f32]) {
18 if s.ascending {
19 data.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
20 } else {
21 data.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
22 }
23}
24
25pub fn sort_apply_str(s: &SortStrategy, data: &mut [String]) {
26 if s.ascending {
27 data.sort();
28 } else {
29 data.sort_by(|a, b| b.cmp(a));
30 }
31}
32
33pub fn sort_is_ascending(s: &SortStrategy) -> bool {
34 s.ascending
35}
36
37pub fn sort_strategy_name(s: &SortStrategy) -> &str {
38 &s.name
39}
40
41pub fn sort_reverse(s: &mut SortStrategy) {
42 s.ascending = !s.ascending;
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48
49 #[test]
50 fn test_sort_f32_ascending() {
51 let s = new_sort_strategy("asc", true);
53 let mut v = vec![3.0f32, 1.0, 2.0];
54 sort_apply_f32(&s, &mut v);
55 assert_eq!(v, vec![1.0, 2.0, 3.0]);
56 }
57
58 #[test]
59 fn test_sort_f32_descending() {
60 let s = new_sort_strategy("desc", false);
62 let mut v = vec![3.0f32, 1.0, 2.0];
63 sort_apply_f32(&s, &mut v);
64 assert_eq!(v, vec![3.0, 2.0, 1.0]);
65 }
66
67 #[test]
68 fn test_sort_str_ascending() {
69 let s = new_sort_strategy("alpha", true);
71 let mut v = vec![
72 "banana".to_string(),
73 "apple".to_string(),
74 "cherry".to_string(),
75 ];
76 sort_apply_str(&s, &mut v);
77 assert_eq!(v[0], "apple");
78 }
79
80 #[test]
81 fn test_sort_reverse() {
82 let mut s = new_sort_strategy("asc", true);
84 sort_reverse(&mut s);
85 assert!(!sort_is_ascending(&s));
86 }
87
88 #[test]
89 fn test_sort_strategy_name() {
90 let s = new_sort_strategy("mySort", true);
92 assert_eq!(sort_strategy_name(&s), "mySort");
93 }
94
95 #[test]
96 fn test_sort_is_ascending() {
97 let s = new_sort_strategy("desc", false);
99 assert!(!sort_is_ascending(&s));
100 }
101}