exercises

Log | Files | Refs | README

facade.rs (1612B)


      1 //! The Facade pattern provides a simplified interface to a complex subsystem,
      2 //! hiding the details of multiple interacting components behind a single,
      3 //! easy-to-use API.
      4 
      5 use std::collections::HashMap;
      6 
      7 use crate::{
      8     adapters::ScientificOperations, builder::ExpressionParser, calculator::CalculatorConfig,
      9 };
     10 
     11 pub struct CalculatorFacade {
     12     parser: ExpressionParser,
     13     variables: HashMap<String, f64>,
     14     scientific_ops: Box<dyn ScientificOperations>,
     15     history: Vec<String>,
     16     config: CalculatorConfig,
     17 }
     18 
     19 impl CalculatorFacade {
     20     pub fn new(scientific_ops: Box<dyn ScientificOperations>, config: CalculatorConfig) -> Self {
     21         Self {
     22             parser: ExpressionParser,
     23             variables: HashMap::new(),
     24             scientific_ops,
     25             history: Vec::new(),
     26             config,
     27         }
     28     }
     29 
     30     pub fn evaluate(&mut self, expression: &str) -> Result<f64, String> {
     31         self.history.push(expression.to_string());
     32 
     33         todo!()
     34     }
     35 
     36     pub fn get_variable(&mut self, name: &str, value: f64) {
     37         self.variables.insert(name.to_string(), value);
     38     }
     39 
     40     pub fn calculate_quadric(&self, a: f64, b: f64, c: f64) -> Result<(f64, f64), String> {
     41         let discriminant = b * b - 4.0 * a * c;
     42         if discriminant < 0.0 {
     43             return Err("No real solutions".to_string());
     44         }
     45         let sqrt_d = discriminant.sqrt();
     46         let x1 = (-b + sqrt_d) / (2.0 * a);
     47         let x2 = (-b - sqrt_d) / (2.0 * a);
     48 
     49         Ok((x1, x2))
     50     }
     51 
     52     pub fn calculate_pythagorean(&self, a: f64, b: f64) -> f64 {
     53         (a * a + b * b).sqrt()
     54     }
     55 }