Skip to content

Commit

Permalink
Refactored string build to make use of fold instead of map and collect.
Browse files Browse the repository at this point in the history
  • Loading branch information
jusexton committed Feb 5, 2024
1 parent 15539b8 commit 4f3e05a
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/codewars/binaries.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use std::fmt::Write;

fn code(s: &str) -> String {
s.chars()
.map(|c| {
let int_value = c.to_digit(10).unwrap();
let bits = format!("{:b}", int_value);
let zero_count = bits.len() - 1;
format!("{}1{}", "0".repeat(zero_count), bits)
})
.collect()
s.chars().fold(String::new(), |mut acc, curr| {
let int_value = curr.to_digit(10).unwrap();
let bits = format!("{:b}", int_value);
let zero_count = bits.len() - 1;
write!(acc, "{}1{}", "0".repeat(zero_count), bits).expect("Buffer write failed.");
acc
})
}

fn decode(s: &str) -> String {
Expand Down

0 comments on commit 4f3e05a

Please sign in to comment.