rustlings

solving rustlings ft. dracuxan
git clone [email protected]:dracuxan/rustlings.git
Log | Files | Refs

quiz2.rs (2091B)


      1 // This is a quiz for the following sections:
      2 // - Strings
      3 // - Vecs
      4 // - Move semantics
      5 // - Modules
      6 // - Enums
      7 //
      8 // Let's build a little machine in the form of a function. As input, we're going
      9 // to give a list of strings and commands. These commands determine what action
     10 // is going to be applied to the string. It can either be:
     11 // - Uppercase the string
     12 // - Trim the string
     13 // - Append "bar" to the string a specified amount of times
     14 //
     15 // The exact form of this will be:
     16 // - The input is going to be a Vector of 2-length tuples,
     17 //   the first element is the string, the second one is the command.
     18 // - The output element is going to be a vector of strings.
     19 
     20 enum Command {
     21     Uppercase,
     22     Trim,
     23     Append(usize),
     24 }
     25 
     26 mod my_module {
     27     use super::Command;
     28 
     29     // TODO: Complete the function as described above.
     30     pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {
     31         let mut output = Vec::new();
     32 
     33         for (string, command) in input {
     34             let transformed_string = match command {
     35                 Command::Uppercase => string.to_uppercase(),
     36                 Command::Trim => string.trim().to_string(),
     37                 Command::Append(n) => string + &"bar".repeat(n),
     38             };
     39             output.push(transformed_string);
     40         }
     41 
     42         output
     43     }
     44 }
     45 
     46 fn main() {
     47     // You can optionally experiment here.
     48 }
     49 
     50 #[cfg(test)]
     51 mod tests {
     52     // TODO: What do we need to import to have `transformer` in scope?
     53     use super::Command;
     54     use crate::my_module::transformer;
     55 
     56     #[test]
     57     fn it_works() {
     58         let input = vec![
     59             ("hello".to_string(), Command::Uppercase),
     60             (" all roads lead to rome! ".to_string(), Command::Trim),
     61             ("foo".to_string(), Command::Append(1)),
     62             ("bar".to_string(), Command::Append(5)),
     63         ];
     64         let output = transformer(input);
     65 
     66         assert_eq!(
     67             output,
     68             [
     69                 "HELLO",
     70                 "all roads lead to rome!",
     71                 "foobar",
     72                 "barbarbarbarbarbar",
     73             ]
     74         );
     75     }
     76 }