Skip to content
Memoize functions - an optimization technique used to speed up consecutive function calls by caching the result of calls with identical input
JavaScript
Latest commit 65d4ab7 Feb 2, 2016 @sindresorhus 0.1.1
Failed to load latest commit information.
.editorconfig init Dec 21, 2015
.gitattributes init Dec 21, 2015
.gitignore init Dec 21, 2015
.travis.yml Travis CI: Test on Node.js v4.x.x and v5.x.x Dec 30, 2015
index.js fix default cacheKey - fixes #3 Feb 1, 2016
license init Dec 21, 2015
package.json 0.1.1 Feb 2, 2016
readme.md 🐐 Jan 5, 2016
test.js fix default cacheKey - fixes #3 Feb 1, 2016

readme.md

mem Build Status

Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input

Requires at least Node.js 0.12, unless you provide your own cache store.

Install

$ npm install --save mem

Usage

const mem = require('mem');

let i = 0;
const counter = () => ++i;
const memoized = mem(counter);

memoized('foo');
//=> 1

// cached as it's the same arguments
memoized('foo');
//=> 1

// not cached anymore as the arguments changed
memoized('bar');
//=> 2

memoized('bar');
//=> 2
Works fine with promise returning functions
const mem = require('mem');

let i = 0;
const counter = () => Promise.resolve(++i);
const memoized = mem(counter);

memoized().then(a => {
    console.log(a);
    //=> 1

    memoized().then(b => {
        // the return value didn't increase as it's cached
        console.log(b);
        //=> 1
    });
});
const mem = require('mem');
const got = require('got');
const memGot = mem(got, {maxAge: 1000});

memGot('sindresorhus.com').then(() => {
    // this call is cached
    memGot('sindresorhus.com').then(() => {
        setTimeout(() => {
            // this call is not cached as the cache has expired
            memGot('sindresorhus.com').then(() => {});
        }, 2000);
    });
});

API

mem(input, [options])

input

Type: function

Function to be memoized.

options

maxAge

Type: number
Default: Infinity

Milliseconds until the cache expires.

cacheKey

Type: function

Determines the cache key for storing the result based on the function arguments. By default, if there's only one argument and it's a primitive it's used directly as a key, otherwise it's all the function arguments JSON stringified as an array.

You could for example change it to only cache on the first argument x => JSON.stringify(x).

cache

Type: object
Default: new Map()

Use a different cache storage. Must implement the following methods: .has(key), .get(key), .set(key, value). You could for example use a WeakMap instead.

License

MIT © Sindre Sorhus

Something went wrong with that request. Please try again.