SkillAgentSearch skills...

Memoizee

Complete memoize/cache solution for JavaScript

Install / Use

/learn @medikoo/Memoizee
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

[![Build status][build-image]][build-url] [![Tests coverage][cov-image]][cov-url] [![npm version][npm-image]][npm-url]

Memoizee

Complete memoize/cache solution for JavaScript

Originally derived from es5-ext package.

Memoization is best technique to save on memory or CPU cycles when we deal with repeated operations. For detailed insight see: http://en.wikipedia.org/wiki/Memoization

Features

Installation

In your project path — note the two e's in memoizee:

$ npm install memoizee
# or with yarn
$ yarn add memoizee

memoize name was already taken, therefore project is published as memoizee on NPM.

To port it to Browser or any other (non CJS) environment, use your favorite CJS bundler. No favorite yet? Try: Browserify, Webmake or Webpack

Usage

var memoize = require("memoizee");

var fn = function (one, two, three) { /* ... */ };

memoized = memoize(fn);

memoized("foo", 3, "bar");
memoized("foo", 3, "bar"); // Cache hit

Note: Invocations that throw exceptions are not cached.

Configuration

All below options can be applied in any combination

Arguments length

By default fixed number of arguments that function take is assumed (it's read from function's length property) this can be overridden:

memoized = memoize(fn, { length: 2 });

memoized("foo"); // Assumed: 'foo', undefined
memoized("foo", undefined); // Cache hit

memoized("foo", 3, {}); // Third argument is ignored (but passed to underlying function)
memoized("foo", 3, 13); // Cache hit

Note: Parameters predefined with default values (ES2015+ feature) are not reflected in function's length, therefore if you want to memoize them as well, you need to tweak length setting accordingly

Dynamic length behavior can be forced by setting length to false, that means memoize will work with any number of arguments.

memoized = memoize(fn, { length: false });

memoized("foo");
memoized("foo"); // Cache hit
memoized("foo", undefined);
memoized("foo", undefined); // Cache hit

memoized("foo", 3, {});
memoized("foo", 3, 13);
memoized("foo", 3, 13); // Cache hit

Primitive mode

If we work with large result sets, or memoize hot functions, default mode may not perform as fast as we expect. In that case it's good to run memoization in primitive mode. To provide fast access, results are saved in hash instead of an array. Generated hash ids are result of arguments to string conversion. Mind that this mode will work correctly only if stringified arguments produce unique strings.

memoized = memoize(fn, { primitive: true });

memoized("/path/one");
memoized("/path/one"); // Cache hit

Cache id resolution (normalization)

By default cache id for given call is resolved either by:

  • Direct Comparison of values passed in arguments as they are. In such case two different objects, even if their characteristics is exactly same (e.g. var a = { foo: 'bar' }, b = { foo: 'bar' }) will be treated as two different values.
  • Comparison of stringified values of given arguments (primitive mode), which serves well, when arguments are expected to be primitive values, or objects that stringify naturally do unique values (e.g. arrays)

Still above two methods do not serve all cases, e.g. if we want to memoize function where arguments are hash objects which we do not want to compare by instance but by its content.

Writing custom cache id normalizers

There's a normalizer option through which we can pass custom cache id normalization function.

Memoizing on dictionary (object hash) arguments)

if we want to memoize a function where argument is a hash object which we do not want to compare by instance but by its content, then we can achieve it as following:

var mfn = memoize(
  function (hash) {
    // body of memoized function
  },
  {
    normalizer: function (args) {
      // args is arguments object as accessible in memoized function
      return JSON.stringify(args[0]);
    },
  }
);

mfn({ foo: "bar" });
mfn({ foo: "bar" }); // Cache hit

If additionally we want to ensure that our logic works well with different order of properties, we need to imply an additional sorting, e.g.

const deepSortedEntries = object =>
  Object.entries(object)
    .map(([key, value]) => {
      if (value && typeof value === "object") return [key, deepSortedEntries(value)];
      return [key, value];
    })
    .sort();

var mfn = memoize(
  function (hash) {
    // body of memoized function
  },
  {
    normalizer: function (args) {
      // args is arguments object as accessible in memoized function
      return JSON.stringify(deepSortedEntries(args[0]));
    },
  }
);

mfn({ foo: "bar", bar: "foo" });
mfn({ bar: "foo", foo: "bar" }); // Cache hit

Argument resolvers

When we're expecting arguments of certain type it's good to coerce them before doing memoization. We can do that by passing additional resolvers array:

memoized = memoize(fn, { length: 2, resolvers: [String, Boolean] });

memoized(12, [1, 2, 3].length);
memoized("12", true); // Cache hit
memoized({ toString: function () { return "12"; } }, {}); // Cache hit

Note. If your arguments are collections (arrays or hashes) that you want to memoize by content (not by self objects), you need to cast them to strings, for it's best to just use primitive mode. Arrays have standard string representation and work with primitive mode out of a box, for hashes you need to define toString method, that will produce unique string descriptions, or rely on JSON.stringify.

Similarly if you want to memoize functions by their code representation not by their objects, you should use primitive mode.

Memoizing asynchronous functions

Promise returning functions

With promise option we indicate that we memoize a function that returns promise.

The difference from natural behavior is that in case when promise was rejected with exception, the result is immediately removed from memoize cache, and not kept as further reusable result.

var afn = function (a, b) {
  return new Promise(function (res) { res(a + b); });
};
memoized = memoize(afn, { promise: true });

memoized(3, 7);
memoized(3, 7); // Cache hit
Important notice on internal promises handling

Default handling stands purely on then which has side-effect of muting eventual unhandled rejection notifications. Alternatively we can other (explained below), by stating with promise option desired mode:

memoized = memoize(afn, { promise: "done:finally" });

Supported modes

  • then (default). Values are resolved purely by passing callbacks to promise.then. Side effect is that eventual unhandled rejection on given promise come with no logged warning!, and that to avoid implied error swallowing both states are resolved tick after callbacks were invoked

  • done Values are resolved purely by passing callback to done method. Side effect is that eventual unhandled rejection on given promise come with no logged warning!.

  • done:finally The only method that may work with no side-effects assuming that promise implementaion does not throw unconditionally if no onFailure callback was passed to done, and promise error was handled by other consumer (this is not commonly implemented done behavior). Otherwise side-effect is that exception is thrown on promise rejection (highly not recommended)

Node.js callback style functions

With async option we indicate that we memoize asynchronous (Node.js style) function Operations that result with an error are not cached.

afn = function (a, b, cb) {
  setTimeout(function () { cb(null, a + b); }, 200);
};
memoized = memoize(afn, { async: true });

memoized(3, 7, function (err, res) {
  memoized(3, 7, function (err, res) {
    // Cache hit
  });
});

memoized(3, 7, function (err, res) {
  // Cache hit
});

Memoizing methods

When we are defining a prototype, we may want to define a method that will memoize it's results in relation to each instance. A basic way to obtain that would be:

var Foo = function () {
  this.bar = memoize(this.bar.bind(this), { someOption: true });
  // ... constructor logic
};
Foo.prototype.bar = function () {
  // ... method logic
};

There's a lazy methods descriptor generator provided:

View on GitHub
GitHub Stars1.8k
CategoryDevelopment
Updated1d ago
Forks64

Languages

JavaScript

Security Score

95/100

Audited on Mar 28, 2026

No findings