Last active
January 5, 2021 02:49
-
-
Save bradclawsie/0e3ef899e04802a6cdc6101e384e89fb to your computer and use it in GitHub Desktop.
typescript lru
This file contains hidden or 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
class lru { | |
size: number; | |
n: number; | |
key2val: Map<string, any>; | |
keys: string[]; | |
constructor(size: number) { | |
this.size = size; | |
this.n = 0; | |
this.key2val = new Map<string,any>(); | |
this.keys = Array<string>(size).fill(""); | |
} | |
get(key: string) { | |
if (this.key2val.has(key)) { | |
let val = this.key2val.get(key); | |
this.set(key, val); | |
return val; | |
} else { | |
return undefined; | |
} | |
} | |
set(key: string, val: any) { | |
let found: boolean = false; | |
this.keys = this.keys.filter(function f(element, index, array) { | |
if (element === key) { | |
found = true; | |
return false; | |
} else { | |
return true; | |
} | |
}); | |
if (!found) { | |
const rm = this.keys.pop(); | |
if ((typeof rm === "string") && (rm !== "")) { | |
this.key2val.delete(rm); | |
} | |
} | |
this.keys.unshift(key); | |
this.key2val.set(key, val); | |
} | |
print(): void { | |
console.log(`keys: ${this.keys}`); | |
} | |
} | |
let l = new lru(3); | |
l.print(); | |
l.set('a',1); | |
l.print(); | |
l.set('b',2); | |
l.print(); | |
l.set('c',3); | |
l.print(); | |
console.log(l.get('a')); | |
l.print(); | |
l.set('d',4); | |
l.print(); | |
console.log(l.get('b')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment