This commit is contained in:
darenhsu
2022-07-17 13:16:16 +08:00
parent 84759556ff
commit befd344ab0
28070 changed files with 4008428 additions and 1 deletions
+108
View File
@@ -0,0 +1,108 @@
declare namespace mem {
interface CacheStorage<KeyType, ValueType> {
has(key: KeyType): boolean;
get(key: KeyType): ValueType | undefined;
set(key: KeyType, value: ValueType): void;
delete(key: KeyType): void;
clear?: () => void;
}
interface Options<
ArgumentsType extends unknown[],
CacheKeyType,
ReturnType
> {
/**
Milliseconds until the cache expires.
@default Infinity
*/
readonly maxAge?: number;
/**
Determines the cache key for storing the result based on the function arguments. By default, __only the first argument is considered__ and it only works with [primitives](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
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:
```
import mem = require('mem');
mem(function_, {cacheKey: JSON.stringify});
```
Or you can use a more full-featured serializer like [serialize-javascript](https://github.com/yahoo/serialize-javascript) to add support for `RegExp`, `Date` and so on.
```
import mem = require('mem');
import serializeJavascript = require('serialize-javascript');
mem(function_, {cacheKey: serializeJavascript});
```
@default arguments_ => arguments_[0]
@example arguments_ => JSON.stringify(arguments_)
*/
readonly cacheKey?: (arguments: ArgumentsType) => CacheKeyType;
/**
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`](https://github.com/sindresorhus/quick-lru) for a LRU cache.
@default new Map()
@example new WeakMap()
*/
readonly cache?: CacheStorage<CacheKeyType, {data: ReturnType; maxAge: number}>;
}
}
declare const mem: {
/**
[Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.
@param fn - Function to be memoized.
@example
```
import 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
```
*/
<
ArgumentsType extends unknown[],
ReturnType,
CacheKeyType,
FunctionToMemoize = (...arguments: ArgumentsType) => ReturnType
>(
fn: FunctionToMemoize,
options?: mem.Options<ArgumentsType, CacheKeyType, ReturnType>
): FunctionToMemoize;
/**
Clear all cached data of a memoized function.
@param fn - Memoized function.
*/
clear<ArgumentsType extends unknown[], ReturnType>(
fn: (...arguments: ArgumentsType) => ReturnType
): void;
};
export = mem;
Generated Vendored
+64
View File
@@ -0,0 +1,64 @@
'use strict';
const mimicFn = require('mimic-fn');
const mapAgeCleaner = require('map-age-cleaner');
const cacheStore = new WeakMap();
const mem = (fn, options = {}) => {
// Automatically use WeakMap unless the user provided their own cache
const weakCache = options.cache || new WeakMap();
const {
cacheKey = ([firstArgument]) => firstArgument,
cache = new Map(),
maxAge
} = options;
if (typeof maxAge === 'number') {
mapAgeCleaner(cache);
}
const memoized = function (...arguments_) {
const key = cacheKey(arguments_);
// Prefer WeakMap if the key allows it
const bestCache = key && (typeof key === 'object' || typeof key === 'function') ?
weakCache :
cache;
if (bestCache.has(key)) {
return bestCache.get(key).data;
}
const cacheItem = fn.apply(this, arguments_);
bestCache.set(key, {
data: cacheItem,
maxAge: maxAge ? Date.now() + maxAge : Infinity
});
return cacheItem;
};
try {
// The below call will throw in some host environments
// See https://github.com/sindresorhus/mimic-fn/issues/10
mimicFn(memoized, fn);
} catch (_) {}
cacheStore.set(memoized, cache);
return memoized;
};
module.exports = mem;
module.exports.clear = fn => {
if (!cacheStore.has(fn)) {
throw new Error('Can\'t clear a function that was not memoized!');
}
const cache = cacheStore.get(fn);
if (typeof cache.clear === 'function') {
cache.clear();
}
};
Generated Vendored
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+81
View File
@@ -0,0 +1,81 @@
{
"_args": [
[
"mem@6.1.0",
"/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series"
]
],
"_from": "mem@6.1.0",
"_id": "mem@6.1.0",
"_inBundle": false,
"_integrity": "sha512-RlbnLQgRHk5lwqTtpEkBTQ2ll/CG/iB+J4Hy2Wh97PjgZgXgWJWrFF+XXujh3UUVLvR4OOTgZzcWMMwnehlEUg==",
"_location": "/mem",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "mem@6.1.0",
"name": "mem",
"escapedName": "mem",
"rawSpec": "6.1.0",
"saveSpec": null,
"fetchSpec": "6.1.0"
},
"_requiredBy": [
"/webpack-external-import"
],
"_resolved": "https://registry.npmjs.org/mem/-/mem-6.1.0.tgz",
"_spec": "6.1.0",
"_where": "/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/mem/issues"
},
"dependencies": {
"map-age-cleaner": "^0.1.3",
"mimic-fn": "^3.0.0"
},
"description": "Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input",
"devDependencies": {
"ava": "^2.4.0",
"delay": "^4.1.0",
"serialize-javascript": "^2.1.0",
"tsd": "^0.11.0",
"xo": "^0.25.3"
},
"engines": {
"node": ">=8"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/sindresorhus/mem#readme",
"keywords": [
"memoize",
"function",
"mem",
"memoization",
"cache",
"caching",
"optimize",
"performance",
"ttl",
"expire",
"promise"
],
"license": "MIT",
"name": "mem",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/mem.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "6.1.0"
}
Generated Vendored
+255
View File
@@ -0,0 +1,255 @@
# mem [![Build Status](https://travis-ci.org/sindresorhus/mem.svg?branch=master)](https://travis-ci.org/sindresorhus/mem)
> [Memoize](https://en.wikipedia.org/wiki/Memoization) 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](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). If you need to cache multiple arguments or cache `object`s *by value*, have a look at alternative [caching strategies](#caching-strategy) below.
## Install
```
$ npm install mem
```
## Usage
```js
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
```js
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
})();
```
```js
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');
})();
```
### Caching strategy
By default, only the first argument is compared via exact equality (`===`) to determine whether a call is identical.
```js
const power = mem((a, b) => Math.power(a, b));
power(2, 2); // => 4, stored in cache with the key 2 (number)
power(2, 3); // => 4, retrieved from cache at key 2 (number), it's wrong
```
You will have to use the `cache` and `cacheKey` options appropriate to your function. In this specific case, the following could work:
```js
const power = mem((a, b) => Math.power(a, b), {
cacheKey: arguments_ => arguments_.join(',')
});
power(2, 2); // => 4, stored in cache with the key '2,2' (both arguments as one string)
power(2, 3); // => 8, stored in cache with the key '2,3'
```
More advanced examples follow.
#### Example: Options-like argument
If your function accepts an object, it won't be memoized out of the box:
```js
const heavyMemoizedOperation = mem(heavyOperation);
heavyMemoizedOperation({full: true}); // Stored in cache with the object as key
heavyMemoizedOperation({full: true}); // Stored in cache with the object as key, again
// The objects look the same but for JS they're two different objects
```
You might want to serialize or hash them, for example using `JSON.stringify` or something like [serialize-javascript](https://github.com/yahoo/serialize-javascript), which can also serialize `RegExp`, `Date` and so on.
```js
const heavyMemoizedOperation = mem(heavyOperation, {cacheKey: JSON.stringify});
heavyMemoizedOperation({full: true}); // Stored in cache with the key '[{"full":true}]' (string)
heavyMemoizedOperation({full: true}); // Retrieved from cache
```
The same solution also works if it accepts multiple serializable objects:
```js
const heavyMemoizedOperation = mem(heavyOperation, {cacheKey: JSON.stringify});
heavyMemoizedOperation('hello', {full: true}); // Stored in cache with the key '["hello",{"full":true}]' (string)
heavyMemoizedOperation('hello', {full: true}); // Retrieved from cache
```
#### Example: Multiple non-serializable arguments
If your function accepts multiple arguments that aren't supported by `JSON.stringify` (e.g. DOM elements and functions), you can instead extend the initial exact equality (`===`) to work on multiple arguments using [`many-keys-map`](https://github.com/fregante/many-keys-map):
```js
const ManyKeysMap = require('many-keys-map');
const addListener = (emitter, eventName, listener) => emitter.on(eventName, listener);
const addOneListener = mem(addListener, {
cacheKey: arguments_ => arguments_, // Use *all* the arguments as key
cache: new ManyKeysMap() // Correctly handles all the arguments for exact equality
});
addOneListener(header, 'click', console.log); // `addListener` is run, and it's cached with the `arguments` array as key
addOneListener(header, 'click', console.log); // `addListener` is not run again
addOneListener(mainContent, 'load', console.log); // `addListener` is run, and it's cached with the `arguments` array as key
```
Better yet, if your function’s arguments are compatible with `WeakMap`, you should use [`deep-weak-map`](https://github.com/futpib/deep-weak-map) instead of `many-keys-map`. This will help avoid memory leaks.
## 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).
Refer to the [caching strategies](#caching-strategy) section for more information.
##### cache
Type: `object`\
Default: `new Map()`, but it also intelligently uses `new WeakMap()` whenevever possible
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 [`quick-lru`](https://github.com/sindresorhus/quick-lru) for a LRU cache.
Refer to the [caching strategies](#caching-strategy) section for more information.
### 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](https://github.com/SamVerschueren/stats-map) as a replacement for the default cache.
#### Example
```js
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}
})();
```
## Related
- [p-memoize](https://github.com/sindresorhus/p-memoize) - Memoize promise-returning & async functions
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-mem?utm_source=npm-mem&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>