From 86f08875a8a00384cbbcb333ae10531fe6dfcccf Mon Sep 17 00:00:00 2001 From: Alexandre Stein Date: Fri, 9 Dec 2022 15:52:01 +0100 Subject: [PATCH] One bracket is working Signed-off-by: Alexandre Stein --- rust-calc/src/main.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/rust-calc/src/main.rs b/rust-calc/src/main.rs index cb078aa..e1d5031 100644 --- a/rust-calc/src/main.rs +++ b/rust-calc/src/main.rs @@ -66,7 +66,6 @@ impl TmpNum { } // Returns the float number from the parsed input fn get(&mut self) -> f64 { - println!("XXX {}", self.s); let n = self.s.parse::().ok().expect("number is malformed"); self.s = String::new(); @@ -147,7 +146,10 @@ fn parse(pattern: String) -> (Vec, Vec) { i = i2; // Check the symbol after the closing bracket - let c3 = pattern.chars().nth(i2 + 1).expect("some char"); + let c3 = match pattern.chars().nth(i2 + 1){ + Some(c) => c, + None => break, + }; if !c3.is_numeric() { let s2 = match c3 { '-' => Some(Symbol::Minus), @@ -322,7 +324,6 @@ fn main() { process::exit(2); } - let res = calculation(symbols, numbers); println!("{res}"); } @@ -356,4 +357,24 @@ mod tests { let (s, n) = parse("30/4-9".to_string()); assert_eq!(calculation(s, n), -1.5); } + + #[test] + fn negative_number() { + let (s, n) = parse("-2*4+4".to_string()); + assert_eq!(calculation(s, n), -4.0); + let (s, n) = parse("-2+2*4".to_string()); + assert_eq!(calculation(s, n), 6.0); + } + + #[test] + fn with_1_bracket_set() { + let (s, n) = parse("2*(4+4)*2".to_string()); + assert_eq!(calculation(s, n), 32.0); + let (s, n) = parse("2*(4+4)".to_string()); + assert_eq!(calculation(s, n), 16.0); + let (s, n) = parse("-2*(4+4)".to_string()); + assert_eq!(calculation(s, n), -16.0); + let (s, n) = parse("(4+4)*2".to_string()); + assert_eq!(calculation(s, n), 16.0); + } }