-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
perf: reduce duplicate rendering in localSearch (#3170)
Co-authored-by: Divyansh Singh <[email protected]>
- Loading branch information
Showing
2 changed files
with
39 additions
and
4 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// adapted from https://stackoverflow.com/a/46432113/11613622 | ||
|
||
export class LRUCache<K, V> { | ||
private max: number | ||
private cache: Map<K, V> | ||
|
||
constructor(max: number = 10) { | ||
this.max = max | ||
this.cache = new Map<K, V>() | ||
} | ||
|
||
get(key: K): V | undefined { | ||
let item = this.cache.get(key) | ||
if (item !== undefined) { | ||
// refresh key | ||
this.cache.delete(key) | ||
this.cache.set(key, item) | ||
} | ||
return item | ||
} | ||
|
||
set(key: K, val: V): void { | ||
// refresh key | ||
if (this.cache.has(key)) this.cache.delete(key) | ||
// evict oldest | ||
else if (this.cache.size === this.max) this.cache.delete(this.first()!) | ||
this.cache.set(key, val) | ||
} | ||
|
||
first(): K | undefined { | ||
return this.cache.keys().next().value | ||
} | ||
} |