Closed charliethomson closed 4 years ago
Any news on this?
Aside from the comments above, looks good overall.
It's not strictly necessary, but you might consider making the translation table a dedicated type (as @kbknapp had done in #56). If so, it might make sense to convert maketrans
to TranslateTable::new
, e.g.,
impl TranslateTable {
pub fn new(f: &str, t: &str) -> Result<Self, String> {
/* ... */
}
/* ... */
}
Note: See additional discussion/review of some of the code in this PR in #62
Oh, also. Could you delete the Python source for condputs
and condputs_tr
as part of this branch?
pub struct TranslationTable {
table: HashMap<char, char>,
} impl TranslationTable {
pub fn new(f: &str, t: &str) -> Result<Self, &'static str> {
if f.len() != t.len() {
Err("Arguments passed to maketrans must have equal length")
} else {
Ok(TranslationTable { table: HashMap::from_iter(f.chars().zip(t.chars())) })
}
}
pub fn translate(&self, s: String) -> String {
s
.chars()
.map(|c| *self.table.get(&c).unwrap_or(&c))
.collect::<String>()
}
}
Thoughts?
pub struct TranslationTable { table: HashMap<char, char>, } impl TranslationTable { pub fn new(f: &str, t: &str) -> Result<Self, &'static str> { if f.len() != t.len() { Err("Arguments passed to maketrans must have equal length") } else { Ok(TranslationTable { table: HashMap::from_iter(f.chars().zip(t.chars())) }) } } pub fn translate(&self, s: String) -> String { s .chars() .map(|c| *self.table.get(&c).unwrap_or(&c)) .collect::<String>() } }
Thoughts?
Very close. You'll want to check character length instead of byte length, since we're operating on characters. (You can use the char_len
function in main.rs
for that.)
Also, you'll want to tweak the error message to be
"Arguments passed to `TranslationTable::new` must have equal character length"
Donezo, anything else?
I combined
condputs
andcondputs_tr
, because one overloads the other later on. I also changed the type ofDeroffer:self.tr
fromString
toOption<HashMap<char, char>>
in order to be able to interface withutil:translate
andutil:maketrans
. In addition, I set the type ofDeroffer:self.output
toString