Skip to content

Commit e0831cd

Browse files
committed
refactor
1 parent 1e654e9 commit e0831cd

File tree

1 file changed

+6
-10
lines changed
  • rust/nucleotide-count/src

1 file changed

+6
-10
lines changed

rust/nucleotide-count/src/lib.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,28 @@
11
use std::collections::HashMap;
22

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

1111
pub fn nucleotide_counts(dna: &str) -> Result<HashMap<char, usize>, char> {
12+
let mut counts = default_counts();
1213
for c in dna.chars() {
13-
if !valid_nucleotide(c) {
14+
if !is_valid_nucleotide(c) {
1415
return Err(c);
1516
}
16-
}
17-
let mut counts: HashMap<char, usize> = default_map();
18-
for c in dna.chars() {
19-
let default: usize = 0;
20-
let v = counts.get(&c).unwrap_or(&default);
21-
counts.insert(c, v + 1);
17+
*counts.entry(c).or_insert(0) += 1;
2218
}
2319
Ok(counts)
2420
}
2521

26-
fn default_map() -> HashMap<char, usize> {
22+
fn default_counts() -> HashMap<char, usize> {
2723
HashMap::from([('A', 0), ('C', 0), ('G', 0), ('T', 0)])
2824
}
2925

30-
fn valid_nucleotide(c: char) -> bool {
26+
fn is_valid_nucleotide(c: char) -> bool {
3127
matches!(c, 'A' | 'C' | 'G' | 'T')
3228
}

0 commit comments

Comments
 (0)