mod ops;
mod test_utils;
use ops::{add, subtract, multiply, divide, AddOp, MulOp, DivOp, Operation, Op};
pub struct Calculator {
pub ops: Vec<Op>,
}
impl Calculator {
pub fn new() -> Self {
Calculator { ops: Vec::new() }
}
pub fn add(&mut self, op: Op) {
self.ops.push(op);
}
pub fn evaluate(&self, a: f64, b: f64) -> f64 {
let mut result = a;
for op in &self.ops {
result = match op {
Op::Add => add(result, b),
Op::Subtract => subtract(result, b),
Op::Multiply => multiply(result, b),
Op::Divide => divide(result, b),
Op::Pow => result.powf(b),
};
}
result
}
}
impl Default for Calculator {
fn default() -> Self {
Self::new()
}
}
pub fn run_operation(op: &dyn Operation, a: f64, b: f64) -> f64 {
op.apply(a, b)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_calculator_add() {
let mut calc = Calculator::new();
calc.add(Op::Add);
assert_eq!(calc.evaluate(3.0, 4.0), 7.0);
}
}