Closure: introduce hashmap to be able to cache several values

This commit is contained in:
laurens 2020-09-27 16:00:25 +02:00
parent 69008722e1
commit c67112b6d3

View file

@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
@ -13,7 +14,7 @@ where
T: Fn(u32) -> u32, T: Fn(u32) -> u32,
{ {
calculation: T, calculation: T,
value: Option<u32>, values: HashMap<u32, u32>,
} }
impl<T> Cacher<T> impl<T> Cacher<T>
@ -23,16 +24,16 @@ where
fn new(calculation: T) -> Cacher<T> { fn new(calculation: T) -> Cacher<T> {
Cacher { Cacher {
calculation, calculation,
value: None, values: HashMap::new(),
} }
} }
fn value(&mut self, arg: u32) -> u32 { fn value(&mut self, arg: u32) -> u32 {
match self.value { match self.values.get(&arg) {
Some(v) => v, Some(v) => *v,
None => { None => {
let v = (self.calculation)(arg); let v = (self.calculation)(arg);
self.value = Some(v); self.values.insert(arg, v);
v v
} }
} }
@ -60,3 +61,19 @@ fn generate_workout(intensity: u32, random_number: u32) {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn call_with_different_values() {
let mut c = Cacher::new(|a| a);
let v1 = c.value(1);
let v2 = c.value(2);
assert_eq!(v1, 1);
assert_eq!(v2, 2);
}
}