From e0831cde489a715b8f0821ddefccbe09ff6aed14 Mon Sep 17 00:00:00 2001 From: Rootul Patel Date: Thu, 9 Jan 2025 22:27:22 -0500 Subject: [PATCH] refactor --- rust/nucleotide-count/src/lib.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/rust/nucleotide-count/src/lib.rs b/rust/nucleotide-count/src/lib.rs index 76f8261b..ddb364c0 100644 --- a/rust/nucleotide-count/src/lib.rs +++ b/rust/nucleotide-count/src/lib.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; pub fn count(nucleotide: char, dna: &str) -> Result { - if !valid_nucleotide(nucleotide) { + if !is_valid_nucleotide(nucleotide) { return Err(nucleotide); } let counts = nucleotide_counts(dna)?; @@ -9,24 +9,20 @@ pub fn count(nucleotide: char, dna: &str) -> Result { } pub fn nucleotide_counts(dna: &str) -> Result, char> { + let mut counts = default_counts(); for c in dna.chars() { - if !valid_nucleotide(c) { + if !is_valid_nucleotide(c) { return Err(c); } - } - let mut counts: HashMap = default_map(); - for c in dna.chars() { - let default: usize = 0; - let v = counts.get(&c).unwrap_or(&default); - counts.insert(c, v + 1); + *counts.entry(c).or_insert(0) += 1; } Ok(counts) } -fn default_map() -> HashMap { +fn default_counts() -> HashMap { HashMap::from([('A', 0), ('C', 0), ('G', 0), ('T', 0)]) } -fn valid_nucleotide(c: char) -> bool { +fn is_valid_nucleotide(c: char) -> bool { matches!(c, 'A' | 'C' | 'G' | 'T') }