summaryrefslogtreecommitdiff
path: root/backend/src/utils/find_by_id_or.rs
diff options
context:
space:
mode:
authorJoe Carstairs <me@joeac.net>2024-09-17 11:28:56 +0100
committerJoe Carstairs <me@joeac.net>2024-09-17 11:28:56 +0100
commitf0e3e0cfb183253e03b1a61ddecb7b9330d47fdb (patch)
tree722eca369743dcfbb95f1efd58cc4cecc0fb8677 /backend/src/utils/find_by_id_or.rs
parentc737b6df94eae4981bb03dda3583e24046e24865 (diff)
Refactors backend
Diffstat (limited to 'backend/src/utils/find_by_id_or.rs')
-rw-r--r--backend/src/utils/find_by_id_or.rs53
1 files changed, 53 insertions, 0 deletions
diff --git a/backend/src/utils/find_by_id_or.rs b/backend/src/utils/find_by_id_or.rs
new file mode 100644
index 0000000..f5add30
--- /dev/null
+++ b/backend/src/utils/find_by_id_or.rs
@@ -0,0 +1,53 @@
+pub fn find_by_id_or<Id: PartialEq, Val: Copy>(
+ arr: &[(Id, Option<Val>)],
+ id: Id,
+ default: Val,
+) -> Val {
+ arr.iter()
+ .find(|(elem_id, _)| *elem_id == id)
+ .map_or(default, |row| match row {
+ (_, Some(quantity)) => *quantity,
+ (_, _) => default,
+ })
+}
+
+#[cfg(test)]
+mod test {
+ use super::find_by_id_or;
+
+ #[test]
+ fn when_no_elements_then_return_default() {
+ let arr = [];
+
+ let result = find_by_id_or(&arr, 1, 42);
+
+ assert_eq!(result, 42);
+ }
+
+ #[test]
+ fn when_id_not_in_elements_then_return_default() {
+ let arr = [(0, Some(100)), (2, Some(200))];
+
+ let result = find_by_id_or(&arr, 1, 42);
+
+ assert_eq!(result, 42);
+ }
+
+ #[test]
+ fn when_value_is_none_then_return_default() {
+ let arr = [(1, None)];
+
+ let result = find_by_id_or(&arr, 1, 42);
+
+ assert_eq!(result, 42);
+ }
+
+ #[test]
+ fn when_value_is_some_then_return_value() {
+ let arr = [(1, Some(67))];
+
+ let result = find_by_id_or(&arr, 1, 42);
+
+ assert_eq!(result, 67);
+ }
+}