aboutsummaryrefslogtreecommitdiff
path: root/src/function_cache.rs
blob: d4beb1651651813cffbb710b87dba8be0ec6a9db (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
use std::collections::HashMap;

use crate::math::{
    complex::Complex, context::Context, expression_function::ExpressionFunction,
    function::{FunctionArgument, Function},
};

#[derive(Default)]
pub struct FunctionCache {
    func: ExpressionFunction,
    cache: HashMap<Complex, Complex>,
}

impl FunctionCache {
    pub fn new(func: ExpressionFunction) -> Self {
        Self {
            func,
            cache: HashMap::new(),
        }
    }

    pub fn eval(&mut self, x: Complex, ctx: &Context) -> Complex {
        if self.cache.contains_key(&x) {
            *self.cache.get(&x).unwrap()
        } else {
            let fargs = FunctionArgument::from_values(vec![x]);
            let v = self.func.eval(&fargs, ctx).unwrap();
            self.cache.insert(x, v);
            v
        }
    }
}