Skip to content

Instantly share code, notes, and snippets.

@siamak
Last active September 20, 2020 15:40
Show Gist options
  • Save siamak/69c110d67a17fcd3bb1b4addcc633cc1 to your computer and use it in GitHub Desktop.
Save siamak/69c110d67a17fcd3bb1b4addcc633cc1 to your computer and use it in GitHub Desktop.
import MemoryCache from "./MemoryCache";
const posts = [
{
id: 1,
title: "Hello World"
},
{
id: 2,
title: "Another Hello";
}
];
const Cache = new MemoryCache();
(async () => {
await Cache.setItem("posts", posts);
console.log(await Cache.getItem('posts'));
})();
class MemoryCache {
memoryStore: Map<string, string>;
constructor() {
this.memoryStore = new Map();
}
async setItem(key: string, value: string): Promise<void> {
this.memoryStore.set(key, value);
}
async getAllKeys(): Promise<string[]> {
return Array.from(this.memoryStore.keys());
}
async getItem(key: string): Promise<string | null> {
if (this.memoryStore.has(key)) {
return this.memoryStore.get(key) as string;
} else {
return null;
}
}
async multiGet(keys: string[]): Promise<any[][]> {
const results: any[][] = [];
for (const key of keys) {
results.push([key, this.getItem(key)]);
}
return results;
}
async multiRemove(keys: string[]): Promise<void> {
for (const key of keys) {
this.memoryStore.delete(key);
}
}
async removeItem(key: string): Promise<void> {
this.memoryStore.delete(key);
}
async clearItem(): Promise<void> {
this.memoryStore.clear();
}
}
export default MemoryCache;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment