Created
November 18, 2023 11:41
-
-
Save valamidev/93c693770267ba6540ec4bbfd89775f7 to your computer and use it in GitHub Desktop.
Performant overlap N/2 continuous cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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