Skip to content

Instantly share code, notes, and snippets.

@dherges
Last active November 17, 2025 20:56
Show Gist options
  • Select an option

  • Save dherges/86012049be7b1263b2e594134ff5816a to your computer and use it in GitHub Desktop.

Select an option

Save dherges/86012049be7b1263b2e594134ff5816a to your computer and use it in GitHub Desktop.
Simple LRU Cache in TypeScript
class LruCache<T> {
private values: Map<string, T> = new Map<string, T>();
private maxEntries: number = 20;
public get(key: string): T {
const hasKey = this.values.has(key);
let entry: T;
if (hasKey) {
// peek the entry, re-insert for LRU strategy
entry = this.values.get(key);
this.values.delete(key);
this.values.set(key, entry);
}
return entry;
}
public put(key: string, value: T) {
if (this.values.size >= this.maxEntries) {
// least-recently used cache eviction strategy
const keyToDelete = this.values.keys().next().value;
this.values.delete(keyToDelete);
}
this.values.set(key, value);
}
}
@adaptive-shield-matrix
Copy link

here my (slightly) adapted version,

following best practices in frontend/js/ts

of "Stop Using JavaScript Classes!" - https://dev.to/giantmachines/stop-using-javascript-classes-33ij

export function createLruCache<T>(maxEntries: number = 20, store: Map<string, T> = new Map<string, T>()) {
  function put(key: string, value: T) {
    if (store.size >= maxEntries) {
      const keyToDelete = store.keys().next().value
      store.delete(keyToDelete)
    }
    store.set(key, value)
  }
  function get(key: string): T | undefined {
    const hasKey = store.has(key)
    if (!hasKey) return undefined

    const entry = store.get(key)!
    store.delete(key)
    store.set(key, entry)
    return entry
  }

  return {
    put,
    get,
    maxEntries,
    store,
  }
}

@sagarpanchal
Copy link

@adaptive-shield-matrix
The article is a rant that proves nothing.
TS and JS both have private class properties.
OOP is way better for entity driven approach.

@adaptive-shield-matrix
Copy link

@sagarpanchal
could you expand more?
I don't know any good cases, where OOP is better.
And I haven't met an entity driven approach in any of the popular frontend frameworks (react, nextjs).
Are you maybe talking about gamedev and not frontend?

@alexey-sh
Copy link

@adaptive-shield-matrix

I don't know any

Consider to learn a bit more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment