use super::{use_ref, Deps, RefContainer};
use std::cell::Ref;
use wasm_bindgen::UnwrapThrowExt;
#[derive(Debug)]
pub struct Memo<T>(RefContainer<Option<T>>);
impl<T: 'static> Memo<T> {
pub fn value(&self) -> Ref<'_, T> {
Ref::map(self.0.current(), |x| {
x.as_ref().expect_throw("no memo data available")
})
}
}
impl<T> Clone for Memo<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
pub fn use_memo<T, D>(create: impl FnOnce() -> T, deps: Deps<D>) -> Memo<T>
where
T: 'static,
D: PartialEq + 'static,
{
let mut deps_ref_container = use_ref(None::<Deps<D>>);
let mut value_ref_container = use_ref(None::<T>);
let need_update = {
let current = deps_ref_container.current();
let old_deps = current.as_ref();
deps.is_all() || Some(&deps) != old_deps
};
if need_update {
deps_ref_container.set_current(Some(deps));
value_ref_container.set_current(Some(create()));
}
Memo(value_ref_container)
}