Last active
September 20, 2020 15:40
-
-
Save siamak/69c110d67a17fcd3bb1b4addcc633cc1 to your computer and use it in GitHub Desktop.
MemoryCache Typescript https://codesandbox.io/s/zen-silence-vcukn?file=/src/index.ts:0-293
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
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')); | |
})(); |
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
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