zavadil-ts-common 1.1.12 → 1.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ export declare class CacheAsync<T> {
2
+ private cache?;
3
+ private supplier;
4
+ private maxAgeMs?;
5
+ private expires?;
6
+ constructor(supplier: () => Promise<T>, maxAgeMs?: number);
7
+ get(): Promise<T>;
8
+ set(v: T): void;
9
+ }
@@ -0,0 +1,9 @@
1
+ export declare class HashCacheAsync<K, V> {
2
+ private cache;
3
+ private supplier;
4
+ constructor(supplier: (k: K) => Promise<V>);
5
+ private obtainCache;
6
+ get(k: K): Promise<V>;
7
+ set(k: K, v: V): void;
8
+ reset(k?: K): void;
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zavadil-ts-common",
3
- "version": "1.1.12",
3
+ "version": "1.1.13",
4
4
  "description": "Common types and components for Typescript UI apps.",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",
@@ -0,0 +1,34 @@
1
+ export class CacheAsync<T> {
2
+
3
+ private cache?: T;
4
+
5
+ private supplier: () => Promise<T>;
6
+
7
+ private maxAgeMs?: number;
8
+
9
+ private expires?: Date;
10
+
11
+ constructor(supplier: () => Promise<T>, maxAgeMs?: number) {
12
+ this.supplier = supplier;
13
+ this.maxAgeMs = maxAgeMs;
14
+ }
15
+
16
+ get(): Promise<T> {
17
+ if (this.cache === undefined || (this.expires && this.expires > new Date())) {
18
+ return this.supplier()
19
+ .then((v: T) => {
20
+ this.set(v);
21
+ return v;
22
+ });
23
+ } else {
24
+ return Promise.resolve(this.cache);
25
+ }
26
+ }
27
+
28
+ set(v: T) {
29
+ this.cache = v;
30
+ if (this.maxAgeMs) {
31
+ this.expires = new Date(new Date().getTime() + this.maxAgeMs);
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,37 @@
1
+ import {CacheAsync} from "./CacheAsync";
2
+
3
+ export class HashCacheAsync<K, V> {
4
+
5
+ private cache = new Map<K, CacheAsync<V>>;
6
+
7
+ private supplier: (k: K) => Promise<V>;
8
+
9
+ constructor(supplier: (k: K) => Promise<V>) {
10
+ this.supplier = supplier;
11
+ }
12
+
13
+ private obtainCache(k: K): CacheAsync<V> {
14
+ let c = this.cache.get(k);
15
+ if (!c) {
16
+ c = new CacheAsync(() => this.supplier(k));
17
+ this.cache.set(k, c);
18
+ }
19
+ return c;
20
+ }
21
+
22
+ get(k: K): Promise<V> {
23
+ return this.obtainCache(k).get();
24
+ }
25
+
26
+ set(k: K, v: V){
27
+ this.obtainCache(k).set(v);
28
+ }
29
+
30
+ reset(k?: K) {
31
+ if (!k) {
32
+ this.cache.clear();
33
+ } else {
34
+ this.cache.delete(k);
35
+ }
36
+ }
37
+ }