JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 31618
  • Score
    100M100P100Q136583F
  • License BSD

Helper for memoizing async functions and methods

Package Exports

  • memoizeasync

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (memoizeasync) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

node-memoizeasync

Yet another memoizer for asynchronous functions.

function myExpensiveComputation(arg1, arg2, cb) {
   // ...
   cb(null, result);
}

var memoized = memoizeAsync(myExpensiveComputation);

Now memoized works exactly like myExpensiveComputation, except that the actual computation is only performed once for each unique set of arguments (apart from the callback):

memoized(42, 100, function (err, result) {
    // Got the result!

    memoized(42, 100, function (err, result) {
        // Got the same result, and much faster this time!
    });
});

The function returned by memoizeAsync invokes the wrapped function in the context it's called in itself, so memoizeAsync even works for memoizing a method that has access to instance variables:

function Foo(name) {
    this.name = name;
}

Foo.prototype.myMethod = memoizeAsync(function (arg1, arg2, cb) {
    console.warn("Cool, this.name works here!", this.name);
    // ...
    cb(null, "That was tough, but I'm done now!");
});

To distinguish different invocations (whose results need to be cached separately) memoizeAsync relies on a naive stringification of the arguments, which is looked up in an internally kept hash. If the function you're memoizing takes non-primitive arguments you might want to provide a custom argumentsStringifier as the second argument to memoizeAsync. Otherwise all object arguments will be considered equal because they stringify to [object Object]:

var memoized = memoizeAsync(function functionToMemoize(obj, cb) {
    // ...
    cb(null, Object.keys(obj).join(''));
}, function argumentStringifier(args) {
   return args.map(function (arg) {return JSON.stringify(arg);}).join(",");
});

memoized({foo: 'bar'}, function (err, result) {
    // result === 'foo'
    memoized({quux: 'baz'}), function (err, result) {
        // result === 'quux'
    });
});

Had the custom argumentsStringifier not been provided, result would have been foo both times.

Check out the custom argumentsStringifier test for another example.

Installation

Make sure you have node.js and npm installed, then run:

npm install memoizeasync

License

3-clause BSD license -- see the LICENSE file for details.