Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
rootulp committed Jan 10, 2025
1 parent 1e654e9 commit e0831cd
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions rust/nucleotide-count/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,32 +1,28 @@
use std::collections::HashMap;

pub fn count(nucleotide: char, dna: &str) -> Result<usize, char> {
if !valid_nucleotide(nucleotide) {
if !is_valid_nucleotide(nucleotide) {
return Err(nucleotide);
}
let counts = nucleotide_counts(dna)?;
Ok(*counts.get(&nucleotide).unwrap())
}

pub fn nucleotide_counts(dna: &str) -> Result<HashMap<char, usize>, 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<char, usize> = 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<char, usize> {
fn default_counts() -> HashMap<char, usize> {
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')
}

0 comments on commit e0831cd

Please sign in to comment.