summaryrefslogtreecommitdiffstats
path: root/cli/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'cli/src/main.rs')
-rw-r--r--cli/src/main.rs31
1 files changed, 13 insertions, 18 deletions
diff --git a/cli/src/main.rs b/cli/src/main.rs
index 22f0da2..7d25b50 100644
--- a/cli/src/main.rs
+++ b/cli/src/main.rs
@@ -146,14 +146,7 @@ fn main() {
SortTarget::Date => transactions.sort_by_key(|t| t.date),
}
for i in 1..sort.len() {
- //TODO macro? dynamic dispatch? trait objects?
- match (&sort[i-1], &sort[i]) {
- (SortTarget::Amount, SortTarget::Date)
- => inner_sort_by_key(&mut transactions, |t| t.amount, |t| t.date),
- (SortTarget::Date, SortTarget::Amount)
- => inner_sort_by_key(&mut transactions, |t| t.date, |t| t.amount),
- _ => panic!(),
- }
+ inner_sort_by(&mut transactions, sort_by_func(&sort[i-1]), sort_by_func(&sort[i]));
}
}
println!("{}", Table::new(transactions).with(Style::psql()));
@@ -161,11 +154,16 @@ fn main() {
}
}
-fn inner_sort_by_key<F, G, K, L, T>(v: &mut [T], mut outer_key: F, mut inner_key: G)
-where F: FnMut(&T) -> K,
- G: FnMut(&T) -> L,
- K: Ord,
- L: Ord,
+fn sort_by_func(sort: &SortTarget) -> impl FnMut(&Transaction, &Transaction) -> std::cmp::Ordering {
+ match sort {
+ SortTarget::Amount => |t1: &Transaction, t2: &Transaction| t1.amount.cmp(&t2.amount),
+ SortTarget::Date => |t1: &Transaction, t2: &Transaction| t1.date.cmp(&t2.date),
+ }
+}
+
+fn inner_sort_by<F, T>(v: &mut [T], mut outer_cmp: F, mut inner_cmp: F)
+where
+ F: FnMut(&T, &T) -> std::cmp::Ordering,
{
// Early out
if v.len() < 2 {
@@ -173,16 +171,13 @@ where F: FnMut(&T) -> K,
}
let mut lower = 0; // Lower bound of current equal range
- let mut last_k = outer_key(&v[0]); // Current key
for i in 0..v.len() {
- let i_k = outer_key(&v[i]);
- if i_k != last_k {
+ if outer_cmp(&v[i], &v[lower]) != std::cmp::Ordering::Equal {
let upper = i;
if upper - lower > 1 {
- v[lower..upper].sort_by_key(&mut inner_key);
+ v[lower..upper].sort_by(&mut inner_cmp);
}
lower = i;
- last_k = i_k;
}
}
}