Wrap localStorage-like storage with per-entry TTL expiry
Browser storage such as localStorage keeps data forever. A web app wants short-lived cache entries (a feature-flag payload for 5 minutes, a draft for a day) that disappear on their own. Build a class, ExpiringStorage, that wraps any storage object and adds a time to live (TTL) to every entry.
const cache = new ExpiringStorage(storage);
storage has the same shape as localStorage: getItem(key) (returns a string or null), setItem(key, string), removeItem(key), key(index) and a length property. Tests pass in an in-memory object with exactly these members.
set(key, value, ttlMs?): store a JSON-serializable value. With ttlMs, the entry expires ttlMs milliseconds after Date.now(); without it, the entry never expires. A ttlMs of 0 or less creates an entry that is already expired. If ttlMs is given but is not a finite number (for example NaN or Infinity), throw a TypeError. Setting a key again replaces both its value and its expiry.get(key): return the stored value (a deserialized copy), or null if the key is missing, expired, or holds data this class did not write. When an entry is found expired, remove it from storage.timeLeft(key): return the remaining milliseconds, Infinity for an entry with no TTL, or null when get would return null. Expired entries are removed here too.remove(key): delete the entry.purgeExpired(): remove every expired entry written by this class from storage and return how many were removed. Leave all other keys alone.Date.now() is greater than or equal to its expiry time. Read the time only with Date.now(); tests replace it with a fake clock.storage under the same key you were given (no prefix), as a string. How you encode the value and expiry inside that string is up to you, but any ExpiringStorage built on the same storage must be able to read it.storage. A value your class cannot read (not JSON, or JSON in a different shape) is treated as missing: get returns null, nothing throws, and the key is not removed.// Date.now() === 1_000
cache.set('flags', { darkMode: true }, 5_000);
cache.set('theme', 'sepia'); // no TTL
cache.get('flags'); // => { darkMode: true }
cache.timeLeft('flags'); // => 5000
cache.timeLeft('theme'); // => Infinity
// Date.now() === 6_000
cache.get('flags'); // => null, and 'flags' is removed from storage
cache.get('theme'); // => 'sepia'
storage.setItem('legacy', 'hello');
cache.get('legacy'); // => null (and 'legacy' stays in storage)
cache.set('a', 1, 10);
cache.set('b', 2, 10);
// Date.now() === 6_010
cache.purgeExpired(); // => 2