Created
March 17, 2019 08:34
-
-
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
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 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