7.1.1 • Published 2 years ago

p-memoize v7.1.1

Weekly downloads
317,064
License
MIT
Repository
github
Last release
2 years ago

p-memoize

Memoize promise-returning & async functions

Useful for speeding up consecutive function calls by caching the result of calls with identical input.

By default, only the memoized function's first argument is considered via strict equality comparison. If you need to cache multiple arguments or cache objects by value, have a look at alternative caching strategies below.

This package is similar to mem but with async-specific enhancements; in particular, it allows for asynchronous caches and does not cache rejected promises.

Install

npm install p-memoize

Usage

import pMemoize from 'p-memoize';
import got from 'got';

const memoizedGot = pMemoize(got);

await memoizedGot('https://sindresorhus.com');

// This call is cached
await memoizedGot('https://sindresorhus.com');

Caching strategy

Similar to the caching strategy for mem with the following exceptions:

  • Promises returned from a memoized function are locally cached until resolving, when their value is added to cache. Special properties assigned to a returned promise will not be kept after resolution and every promise may need to resolve with a serializable object if caching results in a database.
  • .get(), .has() and .set() methods on cache can run asynchronously by returning a promise.
  • Instead of .set() being provided an object with the properties value and maxAge, it will only be provided value as the first argument. If you want to implement time-based expiry, consider doing so in cache.

API

pMemoize(fn, options?)

Returns a memoized version of the given function.

fn

Type: Function

Promise-returning or async function to be memoized.

options

Type: object

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).

See the caching strategy section for more information.

cache

Type: object | false\ 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. To disable caching so that only concurrent executions resolve with the same value, pass false.

See the caching strategy section in the mem package for more information.

pMemoizeDecorator(options)

Returns a decorator to memoize class methods or static class methods.

Notes:

  • Only class methods and getters/setters can be memoized, not regular functions (they aren't part of the proposal);
  • Only TypeScript’s decorators are supported, not Babel’s, which use a different version of the proposal;
  • Being an experimental feature, they need to be enabled with --experimentalDecorators; follow TypeScript’s docs.

options

Type: object

Same as options for pMemoize().

import {pMemoizeDecorator} from 'p-memoize';

class Example {
	index = 0

	@pMemoizeDecorator()
	async counter() {
		return ++this.index;
	}
}

class ExampleWithOptions {
	index = 0

	@pMemoizeDecorator()
	async counter() {
		return ++this.index;
	}
}

pMemoizeClear(memoized)

Clear all cached data of a memoized function.

It will throw when given a non-memoized function.

Tips

Time-based cache expiration

import pMemoize from 'p-memoize';
import ExpiryMap from 'expiry-map';
import got from 'got';

const cache = new ExpiryMap(10000); // Cached values expire after 10 seconds

const memoizedGot = pMemoize(got, {cache});

Caching promise rejections

import pMemoize from 'p-memoize';
import pReflect from 'p-reflect';

const memoizedGot = pMemoize(async (url, options) => pReflect(got(url, options)));

await memoizedGot('https://example.com');
// {isFulfilled: true, isRejected: false, value: '...'}

Related

pageres-screenly@you54f/serverless-offlinecogoportutils@everything-registry/sub-chunk-2396shitsuserverless-offline-node-14serverless-offline-reasintserverless-offline-scalewayserverless-offlineserverless-offline-conioserverless-offline-hot-reloadserverless-offline-imartinezsindresorhus.jssms-number-verifieremail-craftengioscopediscord.js-bycondiscordjs-con-selfrebundledsass-render-errorsredux-libraryremark-krokirerent-serverless-offlinesmartnose-pageresqubit-clic2pa-test-image-service@bee-icons/qwik@beforeyoubid/serverless-offline@swirly/rasterization-servercontentsgartenpromise-fun@coderofsalvation/jsreactor@conio/serverless-offline@connorads/serverless-offlinecleanquirer@block65/kms-jsonwebtoken@block65/memoized@block65/birudacheck-links@authok/express-openid-connect@3fv/serverless-offline@akhilome/npfigma-language-testerflipr-yamlstylelint-sass-render-errorsstreamr-clientexpress-sitemap-xml@sfdocs-internal/check-links@tradle/ethereum-adapter@streamr/sdk@w3block/pixchain-react-metamaskapiref@xflr6/chatbot@xflr6/chatbot-engine@xflr6/chatbot-test@scaffoldly/serverless-offline@stefannienhuis/serverless-offline@snapstrat/serverless-offline@tunnel/mkcert@types/p-memoize@adultswim/express-includes-middleware@1la/jsx-emailtextlint-rule-alive-linktextlint-rule-no-dead-linkexpress-oauth2-bearertint-serverless-offlinejikan-clientjikantszf-np@geut/permanent-seeder-sdkharmony-apivue-npm-publishtomertogo-nptypescript-react-metamask-testunpkgfsjsx-emailinventory-service-v2webext-sandboxheadless-page-watcher@ic_artur/serverless-offline@logsn/client@logsn/streamr-client@librelingo/web@madaster97/fhir-express-openid-connectnext-routes-dir@infinitebrahmanuniverse/nolb-p-ks-serverless-offlinemanage-wifimal-clientmama-exporter@jdion/cast@kaxline/streamr-client@kroonprins/pipectl-azure-devops@juliuste/ecolines@jokeyrhyme/node-init@jsx-email/code@johnpyp/jsx-email@hugojf/serverless-offlinelionp
7.1.1

2 years ago

6.0.2

2 years ago

7.0.0

2 years ago

7.1.0

2 years ago

4.0.4

2 years ago

4.0.3

2 years ago

5.0.1

3 years ago

6.0.1

3 years ago

6.0.0

3 years ago

5.0.0

3 years ago

4.0.2

3 years ago

4.0.1

4 years ago

4.0.0

4 years ago

4.0.0-1

4 years ago

4.0.0-0

4 years ago

3.1.0

5 years ago

3.0.0

5 years ago

2.1.0

6 years ago

2.0.0

6 years ago

1.0.0

8 years ago