Skip to content

Instantly share code, notes, and snippets.

@bradclawsie
Last active Jan 5, 2021
Embed
What would you like to do?
typescript lru
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