Hi there, I'm Marcos!

💾 Simple in-memory cache with JavaScript

class Cache {
  constructor(maxAge) {
    this.store = {};
    this.maxAge = maxAge;
  }

  put = (key, value) => {
    this.store[key] = { timestamp: Date.now(), value };
  };

  get = (key) => {
    if (!(key in this.store)) return null;
    if (Date.now() < this.store[key].timestamp + this.maxAge) {
      return this.store[key].value;
    } else {
      delete this.store[key];
      return null;
    }
  };
}

This is an easy way of setting up an in-memory key-value cache with expiry time in JavaScript. It is based on a plain JavaScript object and you can store value with the put method which will store the value along with the timestamp. The get method will check if the key is in the object and if the item hasn't expired by comparing the current timestamp with the maxAge. If the item has expired it will remove it from the object so that memory is freed up. Note that this is only recommended in development stages because it can make the node process to run out of memory.

Here is an example of how to use it:

const cache = new Cache(1000);

cache.put('id1', 'value1');
cache.get('id1'); // 'value1'

cache.get('id2'); // null

// Some time later
setTimeout(() => {
  cache.get('id1'); // null
}, 1500);