Skip to content

Instantly share code, notes, and snippets.

@henryobiaraije
Created May 19, 2023 20:00
Show Gist options
  • Save henryobiaraije/b14fbe5bdb227e5b0f38f0495473a9e1 to your computer and use it in GitHub Desktop.
Save henryobiaraije/b14fbe5bdb227e5b0f38f0495473a9e1 to your computer and use it in GitHub Desktop.
Calculator code in the calculator library crate.
// Full tutorial https://www.youtube.com/watch?v=LJppDNH2CHI
pub struct Calculator {
result: f64,
}
impl Calculator {
/// Creates a new Calculator instance with the initial result set to 0.0.
pub fn new() -> Self {
return Self { result: 0.0 };
}
/// Adds the values in the provided vector to the calculator's result.
/// Returns a mutable reference to the Calculator instance for method chaining.
pub fn add(&mut self, values: Vec<f64>) -> &mut Self {
for val in values {
self.result += val;
}
return self;
}
/// Subtracts the values in the provided vector from the calculator's result.
/// Returns a mutable reference to the Calculator instance for method chaining.
pub fn subtract(&mut self, values: Vec<f64>) -> &mut Self {
for val in values {
self.result -= val;
}
return self;
}
/// Returns the current result of the calculator.
pub fn get_result(&self) -> f64 {
return self.result;
}
/// Sets the result of the calculator to the specified value.
pub fn set_result(&mut self, result: f64) {
self.result = result;
}
}
#[cfg(test)]
mod test {
use crate::Calculator;
#[test]
fn test_addition() {
let mut calculator = Calculator::new();
calculator.set_result(4.0);
calculator.add([5.0, 5.0].to_vec());
assert_eq!(14.0, calculator.get_result())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment