code improvements

This commit is contained in:
Simon Gardling 2022-04-07 08:47:00 -04:00
parent ed2bdd09e7
commit c10843140b
2 changed files with 26 additions and 25 deletions

View File

@ -311,15 +311,14 @@ where
.map(|x| {
x.as_ref()
.map(|x_1| x_1.to_string())
.unwrap_or("None".to_string())
.unwrap_or_else(|| "None".to_string())
})
.enumerate()
.map(|(i, x)| {
// Add comma and space if needed
if max_i > i as i32 {
return x + ", ";
} else {
return x;
match max_i > i as i32 {
true => x + ", ",
false => x,
}
})
.collect::<Vec<String>>()
@ -347,11 +346,11 @@ pub fn chars_take(chars: &[char], take: usize) -> String {
match take {
0 => {
// return empty string if `take == 0`
return String::new();
String::new()
}
1 => {
// return last character as a string if take == 1
return chars[len - 1].to_string();
chars[len - 1].to_string()
}
_ if take == len => {
// return `chars` turned into a string if `take == len`

View File

@ -44,30 +44,15 @@ impl std::fmt::Debug for HintEnum<'static> {
}
}
// TODO: implement `core::fmt::Display` instead
impl ToString for HintEnum<'static> {
fn to_string(&self) -> String {
match self {
HintEnum::Single(single_data) => single_data.to_string(),
HintEnum::Many(multi_data) => {
let max_i: i32 = (multi_data.len() as i32) - 1;
"[".to_owned()
+ &multi_data
.iter()
.map(|x| r#"""#.to_string() + x + r#"""#)
.enumerate()
.map(|(i, x)| {
// Add comma and space if needed
if max_i > i as i32 {
return x + ", ";
} else {
return x;
}
})
.collect::<Vec<String>>()
.concat() + "]"
format!("{:?}", multi_data)
}
HintEnum::None => String::new(),
HintEnum::None => String::from("None"),
}
}
}
@ -114,4 +99,21 @@ mod tests {
assert_eq!(generate_hint(key), value);
}
}
#[test]
fn hint_to_string_test() {
let values = HashMap::from([
("x^2", HintEnum::Single("x^2")),
(
r#"["n(", "nh(", "gnum("]"#,
HintEnum::Many(&["n(", "nh(", "gnum("]),
),
(r#"["n("]"#, HintEnum::Many(&["n("])),
("None", HintEnum::None),
]);
for (key, value) in values {
assert_eq!(value.to_string(), key);
}
}
}