Custom Lodash Memoize Cache API Structure

This guide outlines the precise API structure required to build a custom cache constructor for overriding _.memoize.Cache in Lodash. You will learn the exact methods your custom cache must implement to remain compatible with Lodash's internal caching mechanism, along with a reference implementation for both global and per-function memoization overrides.

Required Cache Interface

Lodash's memoization relies on an interface modeled directly after the ECMAScript 2015 (ES6) Map specification. When Lodash executes a memoized function, it instantiates your custom constructor using the new operator (new _.memoize.Cache()) to store computed results.

To function correctly, every instance created by your custom constructor must implement the following four core methods:

While not strictly called during basic memoization lookups, implementing a clear() method is recommended to allow consumer code to wipe the cache manually.

Implementation Example

Below is a standard JavaScript class conforming to the required API:

class CustomCache {
  constructor() {
    this.store = {};
  }

  has(key) {
    return Object.prototype.hasOwnProperty.call(this.store, key);
  }

  get(key) {
    return this.store[key];
  }

  set(key, value) {
    this.store[key] = value;
    return this;
  }

  delete(key) {
    if (this.has(key)) {
      delete this.store[key];
      return true;
    }
    return false;
  }

  clear() {
    this.store = {};
  }
}

Overriding the Cache

You can apply a custom cache constructor in two distinct ways: globally across all memoized functions or locally to a specific function instance.

Global Override

Assigning your custom constructor directly to _.memoize.Cache will force all subsequently created memoized functions to use your implementation:

const _ = require('lodash');

// Override globally
_.memoize.Cache = CustomCache;

const expensiveCalculation = (n) => n * 2;
const memoized = _.memoize(expensiveCalculation);

memoized(5); // Cached using CustomCache instance

Per-Function Override

To apply a custom cache without altering the global _.memoize.Cache default, instantiate your cache and assign it directly to the .cache property of the memoized function before calling it:

const _ = require('lodash');

const expensiveCalculation = (n) => n * 2;
const memoized = _.memoize(expensiveCalculation);

// Override for this specific instance only
memoized.cache = new CustomCache();

memoized(10); // Uses this unique CustomCache instance