Skip to content

LRU style atomFamily #1439

Closed Answered by ajoslin
ajoslin asked this question in General
Discussion options

You must be logged in to vote

Awesome - thanks @dai-shi - super simple indeed:

import { PrimitiveAtom } from "jotai";

export type AtomLruFamily<Key, Value> = ((key: Key) => PrimitiveAtom<Value>) & {
  keys: () => Key[];
  onBeforeEvict?: (key: string) => void;
  map: Map<Key, PrimitiveAtom<Value>>;
};

export function atomLruFamily<Key, Value>(
  initializeAtom: (key: Key) => PrimitiveAtom<Value>,
  maxSize = 100
) {
  const cache = new Map();
  const keysSet = new Set<Key>();
  const fn: AtomLruFamily<Key, Value> = (key: Key) => {
    keysSet.delete(key);
    keysSet.add(key);
    if (keysSet.size > maxSize) {
      const firstKey = keysSet.values().next().value;
      fn.onBeforeEvict?.(firstKey);
      keysSet.delete

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Answer selected by ajoslin
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants