Socket
Socket
Sign inDemoInstall

mem

Package Overview
Dependencies
3
Maintainers
1
Versions
29
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    mem

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


Version published
Weekly downloads
5.5M
decreased by-5.16%
Maintainers
1
Install size
33.4 kB
Created
Weekly downloads
 

Readme

Source

mem Build Status

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

Memory is automatically released when an item expires or the cache is cleared.

By default, only the first argument is considered and it only works with primitives. If you need to cache multiple arguments or cache objects by value, use the cacheKey option.

Install

$ npm install 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 argument
memoized('foo');
//=> 1

// Not cached anymore as the argument changed
memoized('bar');
//=> 2

memoized('bar');
//=> 2

// Only the first argument is considered by default
memoized('bar', 'foo');
//=> 2
Works fine with promise returning functions
const mem = require('mem');

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

(async () => {
	console.log(await memoized());
	//=> 1

	// The return value didn't increase as it's cached
	console.log(await memoized());
	//=> 1
})();
const mem = require('mem');
const got = require('got');
const delay = require('delay');

const memGot = mem(got, {maxAge: 1000});

(async () => {
	await memGot('sindresorhus.com');

	// This call is cached
	await memGot('sindresorhus.com');

	await delay(2000);

	// This call is not cached as the cache has expired
	await memGot('sindresorhus.com');
})();

API

mem(fn, options?)

fn

Type: Function

Function to be memoized.

options

Type: object

maxAge

Type: number
Default: Infinity

Milliseconds until the cache expires.

cacheKey

Type: Function
Default: arguments_ => arguments_[0]
Example: arguments_ => JSON.stringify(arguments_)

Determines the cache key for storing the result based on the function arguments. By default, only the first argument is considered.

A cacheKey function can return any type supported by Map (or whatever structure you use in the cache option).

You can have it cache all the arguments by value with JSON.stringify, if they are compatible:

const mem = require('mem');

mem(function_, {cacheKey: JSON.stringify});

Or you can use a more full-featured serializer like serialize-javascript to add support for RegExp, Date and so on.

const mem = require('mem');
const serializeJavascript = require('serialize-javascript');

mem(function_, {cacheKey: serializeJavascript});
cache

Type: object
Default: new Map()

Use a different cache storage. Must implement the following methods: .has(key), .get(key), .set(key, value), .delete(key), and optionally .clear(). You could for example use a WeakMap instead or quick-lru for a LRU cache.

mem.clear(fn)

Clear all cached data of a memoized function.

fn

Type: Function

Memoized function.

Tips

Cache statistics

If you want to know how many times your cache had a hit or a miss, you can make use of stats-map as a replacement for the default cache.

Example
const mem = require('mem');
const StatsMap = require('stats-map');
const got = require('got');

const cache = new StatsMap();
const memGot = mem(got, {cache});

(async () => {
	await memGot('sindresorhus.com');
	await memGot('sindresorhus.com');
	await memGot('sindresorhus.com');

	console.log(cache.stats);
	//=> {hits: 2, misses: 1}
})();
  • p-memoize - Memoize promise-returning & async functions

Get professional support for this package with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

Keywords

FAQs

Last updated on 11 Nov 2019

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc