From c94304cad11af894e13417d46bbe024059e35ca8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alen=20=C5=A0iljak?= Date: Thu, 7 Sep 2023 14:40:54 +0200 Subject: [PATCH] sorting the flattened account structure by name --- src/account.rs | 5 ++++- tests/accounts-tests.rs | 11 ++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/account.rs b/src/account.rs index b53e6b9..1fec747 100644 --- a/src/account.rs +++ b/src/account.rs @@ -173,8 +173,11 @@ impl Account { fn flatten<'a>(&'a self, nodes: &mut Vec<&'a Account>) { // Push the current node to the Vec nodes.push(self); + // + let mut children: Vec<&Account> = self.accounts.values().into_iter().collect(); + children.sort_unstable_by_key(|acc| &acc.name); // If the node has children, recursively call flatten on them - for (_name, child) in &self.accounts { + for child in children { child.flatten(nodes); } } diff --git a/tests/accounts-tests.rs b/tests/accounts-tests.rs index 4f5460a..4ac98b6 100644 --- a/tests/accounts-tests.rs +++ b/tests/accounts-tests.rs @@ -17,9 +17,10 @@ fn test_creating_account_tree() { // Assert let accounts = journal.master.flatten_account_tree(); assert_eq!(5, accounts.len()); - assert_eq!("", accounts.iter().nth(0).unwrap().name); - assert_eq!("Expenses", accounts.iter().nth(1).unwrap().name); - assert_eq!("Food", accounts.iter().nth(2).unwrap().name); - assert_eq!("Assets", accounts.iter().nth(3).unwrap().name); - assert_eq!("Cash", accounts.iter().nth(4).unwrap().name); + let mut iterator = accounts.iter(); + assert_eq!("", iterator.next().unwrap().name); + assert_eq!("Assets", iterator.next().unwrap().name); + assert_eq!("Cash", iterator.next().unwrap().name); + assert_eq!("Expenses", iterator.next().unwrap().name); + assert_eq!("Food", iterator.next().unwrap().name); } \ No newline at end of file