Skip to content

Commit

Permalink
feat(cache): capture and control ttl's on cachable items
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael committed Oct 11, 2022
1 parent 23e088e commit 7fe55ef
Showing 1 changed file with 86 additions and 0 deletions.
86 changes: 86 additions & 0 deletions lib/ttl-cache/cache-clock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { environment } from "../urbex";

type Timeout = null | ReturnType<typeof setTimeout>;
type ClockMap = Map<string, ClockItem>;
type InvokeTimeout = (callback: Function, delay: number) => Timeout;

interface ClockItem {
key: string;
timeout: Timeout;
}

interface ClockOptions {
ttl: number;
onExpire: Function;
}

export class CacheClock {
private _options: ClockOptions;
private _clocks: ClockMap = new Map();

constructor(options?: ClockOptions) {
if (options) {
this.configure(options);
}
}

static create(options: ClockOptions): CacheClock {
return new CacheClock(options);
}

private nativeTimeout(): InvokeTimeout {
if (environment.isNode) {
return global.setTimeout;
}

if (environment.isBrowser) {
return window.setTimeout;
}

return null;
}

configure(options: ClockOptions): void {
this._options = options;
}

add(key: string, ttl: number): void {
if (this._clocks.has(key)) {
this.remove(key);
}

const timeout = this.nativeTimeout();

if (timeout === null) {
return;
}

const item: ClockItem = {
key: key,
timeout: timeout(() => {
this.remove(key);
}, ttl)
};

this._clocks.set(key, item);
}

remove(key: string): void {
const item = this._clocks.get(key);

if (item) {
clearTimeout(item.timeout);
this._clocks.delete(key);
}

if (this._options.onExpire) {
this._options.onExpire(key);
}
}

clear(): void {
for (const [key, item] of this._clocks) {
clearTimeout(item.timeout);
}
}
}

0 comments on commit 7fe55ef

Please sign in to comment.