pax_global_header00006660000000000000000000000064141704770360014523gustar00rootroot0000000000000052 comment=542f8c5c045ad1a52799b82a36fcddc39ca2d3c1 mem-9.0.2/000077500000000000000000000000001417047703600123115ustar00rootroot00000000000000mem-9.0.2/.editorconfig000066400000000000000000000002571417047703600147720ustar00rootroot00000000000000root = true [*] indent_style = tab end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true [*.yml] indent_style = space indent_size = 2 mem-9.0.2/.gitattributes000066400000000000000000000000231417047703600151770ustar00rootroot00000000000000* text=auto eol=lf mem-9.0.2/.github/000077500000000000000000000000001417047703600136515ustar00rootroot00000000000000mem-9.0.2/.github/funding.yml000066400000000000000000000000631417047703600160250ustar00rootroot00000000000000github: [sindresorhus, bfred-it] tidelift: npm/mem mem-9.0.2/.github/security.md000066400000000000000000000002631417047703600160430ustar00rootroot00000000000000# Security Policy To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. mem-9.0.2/.github/workflows/000077500000000000000000000000001417047703600157065ustar00rootroot00000000000000mem-9.0.2/.github/workflows/main.yml000066400000000000000000000006641417047703600173630ustar00rootroot00000000000000name: CI on: - push - pull_request jobs: test: name: Node.js ${{ matrix.node-version }} runs-on: ubuntu-latest strategy: fail-fast: false matrix: node-version: - 16 - 14 - 12 steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} - run: npm install - run: npm test mem-9.0.2/.gitignore000066400000000000000000000000341417047703600142760ustar00rootroot00000000000000node_modules yarn.lock dist mem-9.0.2/.npmrc000066400000000000000000000000231417047703600134240ustar00rootroot00000000000000package-lock=false mem-9.0.2/index.ts000066400000000000000000000124531417047703600137750ustar00rootroot00000000000000import mimicFn from 'mimic-fn'; import mapAgeCleaner from 'map-age-cleaner'; type AnyFunction = (...arguments_: any) => any; const cacheStore = new WeakMap>(); interface CacheStorageContent { data: ValueType; maxAge: number; } interface CacheStorage { has: (key: KeyType) => boolean; get: (key: KeyType) => CacheStorageContent | undefined; set: (key: KeyType, value: CacheStorageContent) => void; delete: (key: KeyType) => void; clear?: () => void; } export interface Options< FunctionToMemoize extends AnyFunction, CacheKeyType, > { /** 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 from '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 from 'mem'; import serializeJavascript from 'serialize-javascript'; mem(function_, {cacheKey: serializeJavascript}); ``` @default arguments_ => arguments_[0] @example arguments_ => JSON.stringify(arguments_) */ readonly cacheKey?: (arguments_: Parameters) => 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>; } /** [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 from 'mem'; let index = 0; const counter = () => ++index; const memoized = mem(counter); memoized('foo'); //=> 1 // Cached as it's the same argument memoized('foo'); //=> 1 // Not cached anymore as the arguments changed memoized('bar'); //=> 2 memoized('bar'); //=> 2 ``` */ export default function mem< FunctionToMemoize extends AnyFunction, CacheKeyType, >( fn: FunctionToMemoize, { cacheKey, cache = new Map(), maxAge, }: Options = {}, ): FunctionToMemoize { if (typeof maxAge === 'number') { mapAgeCleaner(cache as unknown as Map>); } const memoized = function (this: any, ...arguments_: Parameters): ReturnType { const key = cacheKey ? cacheKey(arguments_) : arguments_[0] as CacheKeyType; const cacheItem = cache.get(key); if (cacheItem) { return cacheItem.data; // eslint-disable-line @typescript-eslint/no-unsafe-return } const result = fn.apply(this, arguments_) as ReturnType; cache.set(key, { data: result, maxAge: maxAge ? Date.now() + maxAge : Number.POSITIVE_INFINITY, }); return result; // eslint-disable-line @typescript-eslint/no-unsafe-return } as FunctionToMemoize; mimicFn(memoized, fn, { ignoreNonConfigurable: true, }); cacheStore.set(memoized, cache); return memoized; } /** @returns A [decorator](https://github.com/tc39/proposal-decorators) to memoize class methods or static class methods. @example ``` import {memDecorator} from 'mem'; class Example { index = 0 @memDecorator() counter() { return ++this.index; } } class ExampleWithOptions { index = 0 @memDecorator({maxAge: 1000}) counter() { return ++this.index; } } ``` */ export function memDecorator< FunctionToMemoize extends AnyFunction, CacheKeyType, >( options: Options = {}, ) { const instanceMap = new WeakMap(); return ( target: any, propertyKey: string, descriptor: PropertyDescriptor, ): void => { const input = target[propertyKey]; // eslint-disable-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access if (typeof input !== 'function') { throw new TypeError('The decorated value must be a function'); } delete descriptor.value; delete descriptor.writable; descriptor.get = function () { if (!instanceMap.has(this)) { const value = mem(input, options) as FunctionToMemoize; instanceMap.set(this, value); return value; } return instanceMap.get(this) as FunctionToMemoize; }; }; } /** Clear all cached data of a memoized function. @param fn - Memoized function. */ export function memClear(fn: AnyFunction): void { const cache = cacheStore.get(fn); if (!cache) { throw new TypeError('Can\'t clear a function that was not memoized!'); } if (typeof cache.clear !== 'function') { throw new TypeError('The cache Map can\'t be cleared!'); } cache.clear(); } mem-9.0.2/license000066400000000000000000000021351417047703600136570ustar00rootroot00000000000000MIT License Copyright (c) Sindre Sorhus (https://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. mem-9.0.2/package.json000066400000000000000000000031311417047703600145750ustar00rootroot00000000000000{ "name": "mem", "version": "9.0.2", "description": "Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input", "license": "MIT", "repository": "sindresorhus/mem", "funding": "https://github.com/sindresorhus/mem?sponsor=1", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", "url": "https://sindresorhus.com" }, "type": "module", "exports": "./dist/index.js", "engines": { "node": ">=12.20" }, "scripts": { "test": "xo && ava && npm run build && tsd", "build": "del-cli dist && tsc", "prepack": "npm run build" }, "types": "dist/index.d.ts", "files": [ "dist" ], "keywords": [ "memoize", "function", "mem", "memoization", "cache", "caching", "optimize", "performance", "ttl", "expire", "promise" ], "dependencies": { "map-age-cleaner": "^0.1.3", "mimic-fn": "^4.0.0" }, "devDependencies": { "@ava/typescript": "^1.1.1", "@sindresorhus/tsconfig": "^1.0.2", "@types/serialize-javascript": "^4.0.0", "ava": "^3.15.0", "del-cli": "^3.0.1", "delay": "^4.4.0", "serialize-javascript": "^5.0.1", "ts-node": "^10.1.0", "tsd": "^0.13.1", "typescript": "^4.3.5", "xo": "^0.41.0" }, "ava": { "timeout": "1m", "extensions": { "ts": "module" }, "nonSemVerExperiments": { "configurableModuleFormat": true }, "nodeArguments": [ "--loader=ts-node/esm" ] }, "xo": { "rules": { "@typescript-eslint/member-ordering": "off", "@typescript-eslint/no-var-requires": "off", "@typescript-eslint/no-empty-function": "off" } } } mem-9.0.2/readme.md000066400000000000000000000203731417047703600140750ustar00rootroot00000000000000# 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 memoized function's first argument is considered** via strict equality comparison. If you need to cache multiple arguments or cache `object`s *by value*, have a look at alternative [caching strategies](#caching-strategy) below. If you want to memoize Promise-returning functions (like `async` functions), you might be better served by [p-memoize](https://github.com/sindresorhus/p-memoize). ## Install ``` $ npm install mem ``` ## Usage ```js import mem from 'mem'; let index = 0; const counter = () => ++index; 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 well with Promise-returning functions But you might want to use [p-memoize](https://github.com/sindresorhus/p-memoize) for more Promise-specific behaviors. ```js import mem from 'mem'; let index = 0; const counter = async () => ++index; const memoized = mem(counter); console.log(await memoized()); //=> 1 // The return value didn't increase as it's cached console.log(await memoized()); //=> 1 ``` ```js import mem from 'mem'; import got from 'got'; import delay from 'delay'; const memGot = mem(got, {maxAge: 1000}); await memGot('https://sindresorhus.com'); // This call is cached await memGot('https://sindresorhus.com'); await delay(2000); // This call is not cached as the cache has expired await memGot('https://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 import ManyKeysMap from '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()` 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. Refer to the [caching strategies](#caching-strategy) section for more information. ### memDecorator(options) Returns a [decorator](https://github.com/tc39/proposal-decorators) 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](https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators) are supported, not [Babel’s](https://babeljs.io/docs/en/babel-plugin-proposal-decorators), 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 `mem()`. ```ts import {memDecorator} from 'mem'; class Example { index = 0 @memDecorator() counter() { return ++this.index; } } class ExampleWithOptions { index = 0 @memDecorator({maxAge: 1000}) counter() { return ++this.index; } } ``` ### memClear(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 import mem from 'mem'; import StatsMap from 'stats-map'; import got from 'got'; const cache = new StatsMap(); const memGot = mem(got, {cache}); await memGot('https://sindresorhus.com'); await memGot('https://sindresorhus.com'); await memGot('https://sindresorhus.com'); console.log(cache.stats); //=> {hits: 2, misses: 1} ``` ## Related - [p-memoize](https://github.com/sindresorhus/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.
mem-9.0.2/test-d/000077500000000000000000000000001417047703600135115ustar00rootroot00000000000000mem-9.0.2/test-d/index.test-d.ts000066400000000000000000000040341417047703600163700ustar00rootroot00000000000000import {expectType} from 'tsd'; import mem, {memClear} from '..'; const fn = (text: string) => Boolean(text); expectType(mem(fn)); expectType(mem(fn, {maxAge: 1})); expectType(mem(fn, {cacheKey: ([firstArgument]: [string]) => firstArgument})); expectType( mem(fn, { // The cacheKey returns an array. This isn't deduplicated by a regular Map, but it's valid. The correct solution would be to use ManyKeysMap to deduplicate it correctly cacheKey: (arguments_: [string]) => arguments_, cache: new Map<[string], {data: boolean; maxAge: number}>(), }), ); expectType( // The `firstArgument` of `fn` is of type `string`, so it's used mem(fn, {cache: new Map()}), ); /* Overloaded function tests */ function overloadedFn(parameter: false): false; function overloadedFn(parameter: true): true; function overloadedFn(parameter: boolean): boolean { return parameter; } expectType(mem(overloadedFn)); expectType(mem(overloadedFn)(true)); expectType(mem(overloadedFn)(false)); memClear(fn); // `cacheKey` tests. // The argument should match the memoized function’s parameters mem((text: string) => Boolean(text), { cacheKey: arguments_ => { expectType<[string]>(arguments_); }, }); mem(() => 1, { cacheKey: arguments_ => { expectType<[]>(arguments_); // eslint-disable-line @typescript-eslint/ban-types }, }); // Ensures that the various cache functions infer their arguments type from the return type of `cacheKey` mem((_arguments: {key: string}) => 1, { cacheKey: (arguments_: [{key: string}]) => { expectType<[{key: string}]>(arguments_); return new Date(); }, cache: { get: key => { expectType(key); return { data: 5, maxAge: 2, }; }, set: (key, data) => { expectType(key); expectType<{data: number; maxAge: number}>(data); }, has: key => { expectType(key); return true; }, delete: key => { expectType(key); }, clear: () => undefined, }, }); mem-9.0.2/test.ts000066400000000000000000000151521417047703600136440ustar00rootroot00000000000000import test from 'ava'; import delay from 'delay'; import serializeJavascript from 'serialize-javascript'; import mem, {memDecorator, memClear} from './index.js'; test('memoize', t => { let i = 0; const fixture = () => i++; const memoized = mem(fixture); t.is(memoized(), 0); t.is(memoized(), 0); t.is(memoized(), 0); // @ts-expect-error t.is(memoized(undefined), 0); // @ts-expect-error t.is(memoized(undefined), 0); // @ts-expect-error t.is(memoized('foo'), 1); // @ts-expect-error t.is(memoized('foo'), 1); // @ts-expect-error t.is(memoized('foo'), 1); // @ts-expect-error t.is(memoized('foo', 'bar'), 1); // @ts-expect-error t.is(memoized('foo', 'bar'), 1); // @ts-expect-error t.is(memoized('foo', 'bar'), 1); // @ts-expect-error t.is(memoized(1), 2); // @ts-expect-error t.is(memoized(1), 2); // @ts-expect-error t.is(memoized(null), 3); // @ts-expect-error t.is(memoized(null), 3); // @ts-expect-error t.is(memoized(fixture), 4); // @ts-expect-error t.is(memoized(fixture), 4); // @ts-expect-error t.is(memoized(true), 5); // @ts-expect-error t.is(memoized(true), 5); // Ensure that functions are stored by reference and not by "value" (e.g. their `.toString()` representation) // @ts-expect-error t.is(memoized(() => i++), 6); // @ts-expect-error t.is(memoized(() => i++), 7); }); test('cacheKey option', t => { let i = 0; const fixture = (..._arguments: any) => i++; const memoized = mem(fixture, {cacheKey: ([firstArgument]) => String(firstArgument)}); t.is(memoized(1), 0); t.is(memoized(1), 0); t.is(memoized('1'), 0); t.is(memoized('2'), 1); t.is(memoized(2), 1); }); test('memoize with multiple non-primitive arguments', t => { let i = 0; const memoized = mem(() => i++, {cacheKey: JSON.stringify}); t.is(memoized(), 0); t.is(memoized(), 0); // @ts-expect-error t.is(memoized({foo: true}, {bar: false}), 1); // @ts-expect-error t.is(memoized({foo: true}, {bar: false}), 1); // @ts-expect-error t.is(memoized({foo: true}, {bar: false}, {baz: true}), 2); // @ts-expect-error t.is(memoized({foo: true}, {bar: false}, {baz: true}), 2); }); test('memoize with regexp arguments', t => { let i = 0; const memoized = mem(() => i++, {cacheKey: serializeJavascript}); t.is(memoized(), 0); t.is(memoized(), 0); // @ts-expect-error t.is(memoized(/Sindre Sorhus/), 1); // @ts-expect-error t.is(memoized(/Sindre Sorhus/), 1); // @ts-expect-error t.is(memoized(/Elvin Peng/), 2); // @ts-expect-error t.is(memoized(/Elvin Peng/), 2); }); test('memoize with Symbol arguments', t => { let i = 0; const argument1 = Symbol('fixture1'); const argument2 = Symbol('fixture2'); const memoized = mem(() => i++); t.is(memoized(), 0); t.is(memoized(), 0); // @ts-expect-error t.is(memoized(argument1), 1); // @ts-expect-error t.is(memoized(argument1), 1); // @ts-expect-error t.is(memoized(argument2), 2); // @ts-expect-error t.is(memoized(argument2), 2); }); test('maxAge option', async t => { let i = 0; const fixture = () => i++; const memoized = mem(fixture, {maxAge: 100}); // @ts-expect-error t.is(memoized(1), 0); // @ts-expect-error t.is(memoized(1), 0); await delay(50); // @ts-expect-error t.is(memoized(1), 0); await delay(200); // @ts-expect-error t.is(memoized(1), 1); }); test('maxAge option deletes old items', async t => { let i = 0; const fixture = () => i++; const cache = new Map(); const deleted: number[] = []; const _delete = cache.delete.bind(cache); cache.delete = item => { deleted.push(item); return _delete(item); }; // @ts-expect-error const memoized = mem(fixture, {maxAge: 100, cache}); // @ts-expect-error t.is(memoized(1), 0); // @ts-expect-error t.is(memoized(1), 0); t.is(cache.has(1), true); await delay(50); // @ts-expect-error t.is(memoized(1), 0); t.is(deleted.length, 0); await delay(200); // @ts-expect-error t.is(memoized(1), 1); t.is(deleted.length, 1); t.is(deleted[0], 1); }); test('maxAge items are deleted even if function throws', async t => { let i = 0; const fixture = () => { if (i === 1) { throw new Error('failure'); } return i++; }; const cache = new Map(); const memoized = mem(fixture, {maxAge: 100, cache}); // @ts-expect-error t.is(memoized(1), 0); // @ts-expect-error t.is(memoized(1), 0); t.is(cache.size, 1); await delay(50); // @ts-expect-error t.is(memoized(1), 0); await delay(200); t.throws(() => { // @ts-expect-error memoized(1); }, {message: 'failure'}); t.is(cache.size, 0); }); test('cache option', t => { let i = 0; const fixture = (..._arguments: any) => i++; const memoized = mem(fixture, { cache: new WeakMap(), cacheKey: ([firstArgument]: [ReturnValue]): ReturnValue => firstArgument, }); const foo = {}; const bar = {}; t.is(memoized(foo), 0); t.is(memoized(foo), 0); t.is(memoized(bar), 1); t.is(memoized(bar), 1); }); test('promise support', async t => { let i = 0; const memoized = mem(async () => i++); t.is(await memoized(), 0); t.is(await memoized(), 0); // @ts-expect-error t.is(await memoized(10), 1); }); test('preserves the original function name', t => { t.is(mem(function foo() {}).name, 'foo'); // eslint-disable-line func-names }); test('.clear()', t => { let i = 0; const fixture = () => i++; const memoized = mem(fixture); t.is(memoized(), 0); t.is(memoized(), 0); memClear(memoized); t.is(memoized(), 1); t.is(memoized(), 1); }); test('prototype support', t => { class Unicorn { index = 0; foo() { return this.index++; } } Unicorn.prototype.foo = mem(Unicorn.prototype.foo); const unicorn = new Unicorn(); t.is(unicorn.foo(), 0); t.is(unicorn.foo(), 0); t.is(unicorn.foo(), 0); }); test('.decorator()', t => { let returnValue = 1; const returnValue2 = 101; class TestClass { @memDecorator() counter() { return returnValue++; } @memDecorator() counter2() { return returnValue2; } } const alpha = new TestClass(); t.is(alpha.counter(), 1); t.is(alpha.counter(), 1, 'The method should be memoized'); t.is(alpha.counter2(), 101, 'The method should be memoized separately from the other one'); const beta = new TestClass(); t.is(beta.counter(), 2, 'The method should not be memoized across instances'); }); test('memClear() throws when called with a plain function', t => { t.throws(() => { memClear(() => {}); }, { message: 'Can\'t clear a function that was not memoized!', instanceOf: TypeError, }); }); test('memClear() throws when called on an unclearable cache', t => { const fixture = () => 1; const memoized = mem(fixture, { cache: new WeakMap(), }); t.throws(() => { memClear(memoized); }, { message: 'The cache Map can\'t be cleared!', instanceOf: TypeError, }); }); mem-9.0.2/tsconfig.json000066400000000000000000000002251417047703600150170ustar00rootroot00000000000000{ "extends": "@sindresorhus/tsconfig", "compilerOptions": { "outDir": "dist", "experimentalDecorators": true }, "files": [ "index.ts" ] }