Ad
Mathematics

parses a string, and evaluates it.

Code
Diff
  • const OPS: [char; 4] = ['*', '/', '+', '-'];
    
    fn parse(operator: char, x: i32, y: i32) -> i32 {
        match operator {
            '+' => x + y, '-' => x - y,
            '*' => x * y, '/' => x / y,
            _ => 0 // handled
        }
    }
    
    fn calculator(text: &str) -> i32 {
        let text = text.replace(" ", "");
        let index = text.find(OPS).unwrap();
        
        let operator = text.as_bytes()[index] as char;
        
        let x = text.get(..index).unwrap().parse::<i32>().unwrap(); // unwrap hell
        let y = text.get(index+1..).unwrap().parse::<i32>().unwrap(); // more unwrap hell
        
        println!("{x} {operator} {y} is equal to {}", parse(operator, x, y));
        return parse(operator, x, y);
    }
    • fn calculator(operator: char, num1: i32, num2: i32) -> i32 {
    • const OPS: [char; 4] = ['*', '/', '+', '-'];
    • fn parse(operator: char, x: i32, y: i32) -> i32 {
    • match operator {
    • '+' => num1 + num2,
    • '-' => num1 - num2,
    • '*' => num1 * num2,
    • '/' => num1 / num2,
    • _ => panic!("Invalid operator: '{operator}'.")
    • '+' => x + y, '-' => x - y,
    • '*' => x * y, '/' => x / y,
    • _ => 0 // handled
    • }
    • }
    • fn calculator(text: &str) -> i32 {
    • let text = text.replace(" ", "");
    • let index = text.find(OPS).unwrap();
    • let operator = text.as_bytes()[index] as char;
    • let x = text.get(..index).unwrap().parse::<i32>().unwrap(); // unwrap hell
    • let y = text.get(index+1..).unwrap().parse::<i32>().unwrap(); // more unwrap hell
    • println!("{x} {operator} {y} is equal to {}", parse(operator, x, y));
    • return parse(operator, x, y);
    • }