Skip to content

Instantly share code, notes, and snippets.

@valamidev
Created November 18, 2023 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valamidev/93c693770267ba6540ec4bbfd89775f7 to your computer and use it in GitHub Desktop.
Save valamidev/93c693770267ba6540ec4bbfd89775f7 to your computer and use it in GitHub Desktop.
Performant overlap N/2 continuous cache
export class BucketCache<T> {
private bucket1: Map<string, T>;
private bucket2: Map<string, T>;
private currentBucket: Map<string, T>;
constructor(private readonly N: number) {
this.bucket1 = new Map();
this.bucket2 = new Map();
this.currentBucket = this.bucket1;
}
get(key: string): T | undefined {
const value = this.currentBucket.get(key);
if (value !== undefined) {
return value;
}
const otherBucket =
this.currentBucket === this.bucket1 ? this.bucket2 : this.bucket1;
return otherBucket.get(key);
}
set(key: string, value: T): void {
if (this.currentBucket.size === this.N / 2) {
const otherBucket =
this.currentBucket === this.bucket1 ? this.bucket2 : this.bucket1;
this.currentBucket = otherBucket;
this.currentBucket.clear();
}
this.currentBucket.set(key, value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment