Closure: introduce hashmap to be able to cache several values
This commit is contained in:
parent
69008722e1
commit
c67112b6d3
1 changed files with 22 additions and 5 deletions
|
|
@ -1,3 +1,4 @@
|
|||
use std::collections::HashMap;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
|
|
@ -13,7 +14,7 @@ where
|
|||
T: Fn(u32) -> u32,
|
||||
{
|
||||
calculation: T,
|
||||
value: Option<u32>,
|
||||
values: HashMap<u32, u32>,
|
||||
}
|
||||
|
||||
impl<T> Cacher<T>
|
||||
|
|
@ -23,16 +24,16 @@ where
|
|||
fn new(calculation: T) -> Cacher<T> {
|
||||
Cacher {
|
||||
calculation,
|
||||
value: None,
|
||||
values: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn value(&mut self, arg: u32) -> u32 {
|
||||
match self.value {
|
||||
Some(v) => v,
|
||||
match self.values.get(&arg) {
|
||||
Some(v) => *v,
|
||||
None => {
|
||||
let v = (self.calculation)(arg);
|
||||
self.value = Some(v);
|
||||
self.values.insert(arg, 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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue