From aba3ada87ccc3a09b43d324ed02bc9605fb86bab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Minelli?= <michael@minelli.me> Date: Mon, 3 Jul 2023 16:44:52 +0200 Subject: [PATCH] Add LazyVal class (lazy loading of values) --- helpers/LazyVal.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 helpers/LazyVal.ts diff --git a/helpers/LazyVal.ts b/helpers/LazyVal.ts new file mode 100644 index 0000000..cd97f68 --- /dev/null +++ b/helpers/LazyVal.ts @@ -0,0 +1,26 @@ +class LazyVal<T> { + private val: T = null; + + constructor(private valLoader: () => Promise<T>) {} + + get value(): Promise<T> { + return new Promise<T>(async (resolve) => { + if (this.val === null) { + this.val = await this.valLoader(); + } + + resolve(this.val); + }); + } + + reset() { + this.val = null; + } + + get isValueLoaded(): boolean { + return this.val !== null; + } +} + + +export default LazyVal; -- GitLab