Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 1.6 KiBRawPermalink
1class ClipboardCache {
2 private cache: Map<string, string>;
3 private order: string[];
4 private readonly maxSize = 30;
5
6 constructor() {
7 this.cache = new Map();
8 this.order = [];
9 }
10
11 /*
12 Returns true if added, false if not.
13 */
14 add(id: string, content: string): boolean {
15 if (!content) {
16 return false;
17 }
18
19 // Check if the content already exists in the cache
20 for (const [existingId, existingContent] of this.cache.entries()) {
21 if (existingContent === content) {
22 // Remove the existing entry with the same content
23 this.cache.delete(existingId);
24 const index = this.order.indexOf(existingId);
25 if (index > -1) {
26 this.order.splice(index, 1);
27 }
28 return false;
29 }
30 }
31
32 // Remove the oldest entry if the cache exceeds the maximum size
33 if (this.order.length >= this.maxSize) {
34 const oldest = this.order.pop();
35 if (oldest) {
36 this.cache.delete(oldest);
37 }
38 }
39
40 // Add the new entry to the cache and update the order
41 this.cache.set(id, content);
42 this.order.unshift(id);
43 return true;
44 }
45
46 getNItems(count: number): { id: string; content: string }[] {
47 return this.order.slice(0, count).map((id) => ({
48 id,
49 content: this.cache.get(id) || "",
50 }));
51 }
52
53 get(id: string): string | undefined {
54 return this.cache.get(id);
55 }
56
57 select(id: string): void {
58 const index = this.order.indexOf(id);
59 if (index > -1) {
60 this.order.splice(index, 1);
61 this.order.unshift(id);
62 }
63 }
64
65 clear(): void {
66 this.cache.clear();
67 this.order = [];
68 }
69}
70
71export const clipboardCache = new ClipboardCache();