UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

54 lines (53 loc) 2.3 kB
import type { CommonLogger } from '../log/commonLogger.js'; import type { AnyFunction, AnyObject, MaybeParameters } from '../types.js'; import type { MemoCache, MethodDecorator } from './memo.util.js'; export interface MemoOptions<FN> { /** * Provide a custom implementation of MemoCache. * Function that creates an instance of `MemoCache`. * e.g LRUMemoCache from `@naturalcycles/nodejs-lib` */ cacheFactory?: () => MemoCache; /** * Provide a custom implementation of CacheKey function. */ cacheKeyFn?: (args: MaybeParameters<FN>) => any; /** * Default to `console` */ logger?: CommonLogger; } export interface MemoInstance { /** * Clears the cache. */ clear: () => void; getInstanceCache: () => Map<AnyObject, MemoCache>; getCache: (instance: AnyFunction) => MemoCache | undefined; } /** * Memoizes the method of the class, so it caches the output and returns the cached version if the "key" * of the cache is the same. Key, by defaul, is calculated as `JSON.stringify(...args)`. * Cache is stored indefinitely in the internal Map. * * If origin function throws an Error - it is NOT cached. * So, error-throwing functions will be called multiple times. * Therefor, if the origin function can possibly throw - it should try to be idempotent. * * Cache is stored **per instance** - separate cache for separate instances of the class. * If you don't want it that way - you can use a static method, then there will be only one "instance". * * Supports dropping it's cache by calling .clear() method of decorated function (useful in unit testing). * * Based on: * https://github.com/mgechev/memo-decorator/blob/master/index.ts * http://decodize.com/blog/2012/08/27/javascript-memoization-caching-results-for-better-performance/ * http://inlehmansterms.net/2015/03/01/javascript-memoization/ * https://community.risingstack.com/the-worlds-fastest-javascript-memoization-library/ */ export declare const _Memo: <FN>(opt?: MemoOptions<FN>) => MethodDecorator<FN>; /** Call it on a method that is decorated with `@_Memo` to get access to additional functions, e.g `clear` to clear the cache, or get its underlying data. */ export declare function _getMemo(method: AnyFunction): MemoInstance;