Skip to content

Instantly share code, notes, and snippets.

@alexewerlof
Created March 17, 2019 08:34
Show Gist options
  • Save alexewerlof/5259fe91877ec100208fab40d82fa116 to your computer and use it in GitHub Desktop.
Save alexewerlof/5259fe91877ec100208fab40d82fa116 to your computer and use it in GitHub Desktop.
A typescript class that memoizes a single-argument function `(string) => T` with a limited cache size
export class CachedFn<T> {
private cache: {
[key: string]: T
} = {}
private keys: string[]
private currKeyIndex = 0
constructor(private fn: (arg: string) => T, private size: number = 100) {
this.keys = new Array(size)
}
public clear() {
this.cache = {}
}
public obtain(key: string): T {
let result = this.cache[key]
if (!result) {
result = this.cache[key] = this.fn(key)
const keyToDelete = this.keys[this.currKeyIndex]
if (keyToDelete !== undefined) {
delete this.cache[keyToDelete]
}
this.keys[this.currKeyIndex] = key
this.currKeyIndex++
this.currKeyIndex %= this.size
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment