Added Rates Service: Base, Coinbase, Composite
This commit is contained in:
@@ -1,7 +1,25 @@
|
||||
// TODO: We may want to move this to @xocash/primitives.
|
||||
|
||||
export type MemoizerItem<T> = {
|
||||
value: T;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export class Memoizer {
|
||||
private cache = new Map<string, any>();
|
||||
private cache = new Map<string, MemoizerItem<any>>();
|
||||
|
||||
/**
|
||||
* Sets a cached value for the given key.
|
||||
*
|
||||
* @param key - The key to store the value under
|
||||
* @param value - The value to store
|
||||
*/
|
||||
set(key: string, value: any): void {
|
||||
this.cache.set(key, {
|
||||
value,
|
||||
timestamp: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a cached value for the given key, computing it if it doesn't exist.
|
||||
@@ -10,11 +28,16 @@ export class Memoizer {
|
||||
* @param compute - Function to compute the value if it's not cached
|
||||
* @returns The cached or computed value
|
||||
*/
|
||||
get<K extends string, V>(key: K, compute: () => V): V {
|
||||
if (!this.cache.has(key)) {
|
||||
this.cache.set(key, compute());
|
||||
get<K extends string, V>(key: K, compute: () => V, ttl?: number): V {
|
||||
if (ttl) {
|
||||
this.removeIfExpired(key, ttl);
|
||||
}
|
||||
return this.cache.get(key) as V;
|
||||
|
||||
if (!this.cache.has(key)) {
|
||||
this.set(key, compute());
|
||||
}
|
||||
|
||||
return this.cache.get(key)!.value as V;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -23,7 +46,11 @@ export class Memoizer {
|
||||
* @param key - The key to check
|
||||
* @returns Whether the key exists in the cache
|
||||
*/
|
||||
has(key: string): boolean {
|
||||
has(key: string, ttl?: number): boolean {
|
||||
if (ttl) {
|
||||
this.removeIfExpired(key, ttl);
|
||||
}
|
||||
|
||||
return this.cache.has(key);
|
||||
}
|
||||
|
||||
@@ -52,4 +79,16 @@ export class Memoizer {
|
||||
keys(): string[] {
|
||||
return Array.from(this.cache.keys());
|
||||
}
|
||||
|
||||
private removeIfExpired(key: string, ttl: number): void {
|
||||
if (!this.cache.has(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const item = this.cache.get(key);
|
||||
|
||||
if (Date.now() - item!.timestamp > ttl) {
|
||||
this.cache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user