npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

memoizesync

v1.1.1

Published

Helper for memoizing synchronous functions and methods

Downloads

56,766

Readme

node-memoizesync

Yet another memoizer for synchronous functions.

NPM version Build Status Coverage Status Dependency Status

var memoizeSync = require('memoizesync');

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

var memoized = memoizeSync(myExpensiveComputation, options);

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

var result = memoized(42, 100);
// Got the result!

var result2 = memoized(42, 100);
// Got the same result, and much faster this time!

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

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

    this.myMethod = memoizeSync(function (arg1, arg2) {
        console.log("Cool, this.name works here!", this.name);
        // ...
        return "That was tough, but I'm done now!";
    });
}

(Unfortunately setting Foo.prototype.myMethod = memoizeSync(...) wouldn't work as the memoizer would be shared among all instances of Foo).

To distinguish different invocations (whose results need to be cached separately) memoizeSync 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 in the options argument to memoizeSync. Otherwise all object arguments will be considered equal because they stringify to [object Object]:

var memoized = memoizeSync(function functionToMemoize(obj) {
    // ...
    return Object.keys(obj).join('');
}, {
    argumentsStringifier: function (args) {
        return args.map(function (arg) {return JSON.stringify(arg);}).join(",");
    }
);

memoized({foo: 'bar'}); // 'foo'

memoized({quux: 'baz'}); // 'quux'

Had the custom argumentsStringifier not been provided, the memoized function would would have returned foo both times.

If the argumentsStringifier returns false, the cache will be bypassed.

Check out the custom argumentsStringifier test for another example.

Purging and expiring memoized values

You can forcefully clear a specific memoized value using the purge method on the memoizer:

var memoized = memoizeSync(function functionToMemoize(foo) {
    // ...
    return theResult;
});
var foo = memoized(123);
memoized.purge(123);
foo = memoized(123); // Will be recomputed

memoizer.purgeAll() clears all memoized results.

You can also specify a custom ttl (in milliseconds) on the memoized results:

var memoized = memoizeSync(function functionToMemoize() {
    // ...
    return theResult;
}, {maxAge: 1000});

In the above example the memoized value will be considered stale one second after it has been computed, and it will be recomputed next time memoizeSync is invoked with the same arguments.

memoizeSync uses node-lru-cache to store the memoized values, and it accepts the same parameters in the options object.

If you want to use the length option for lru-cache, note that the memoized values are arrays: [exception, returnValue].

var memoizedFsReadFileSync = memoizeSync(require('fs').readFileSync, {
    max: 1000000,
    length: function (exceptionAndReturnValue) {
        if (exceptionAndReturnValue[0]) {
            return 1;
        } else {
            var body = exceptionAndReturnValue[1];
            return Buffer.isBuffer(body) ? body.length : Buffer.byteLength(body);
        }
    },
    maxAge: 1000
});

The LRU instance is exposed in the cache property of the memoized function in case you need to access it.

Installation

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

npm install memoizesync

Browser compatibility

memoizeSync uses the UMD wrapper, so it should also work in browsers. You should also have the node-lru-cache included:

<script src="lru-cache.js"></script>
<script src="memoizeSync.js"></script>
<script>
    var memoizedFunction = memoizeSync(function () {
        // ...
    });
</script>

lru-cache uses Object.defineProperty and doesn't include an UMD wrapper, but if you define a shims config it should be possible to get it memoizeSync working with require.js, at least in newer browsers.

License

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