Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/playerony/memoize-function
A memoization library that caches all results and supports N arguments with any type.
https://github.com/playerony/memoize-function
Last synced: 4 days ago
JSON representation
A memoization library that caches all results and supports N arguments with any type.
- Host: GitHub
- URL: https://github.com/playerony/memoize-function
- Owner: playerony
- License: mit
- Created: 2021-05-18T19:42:03.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2021-05-22T14:54:35.000Z (over 3 years ago)
- Last Synced: 2023-03-08T05:38:19.867Z (almost 2 years ago)
- Language: TypeScript
- Homepage:
- Size: 159 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# memoize-function
![Lint Check](https://github.com/playerony/memoize-function/workflows/Lint/badge.svg)
![Test Check](https://github.com/playerony/memoize-function/workflows/Test/badge.svg)
![Production Build](https://github.com/playerony/memoize-function/workflows/Build/badge.svg)
![Typecheck Check](https://github.com/playerony/memoize-function/workflows/Typecheck/badge.svg)> In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
> — WikipediaA memoization library that caches all results and supports _N_ arguments with any type.
## Installation
```shell
npm install memoize-function --save
```## Usage
```js
const memoizeFunction = require("memoize-function");const factorial = memoizeFunction((value) => {
if (value <= 1) {
return 1;
}return value * factorial(value - 1);
});factorial(50);
factorial(20); // Value from cache
```### Custom storage
It is possible to pass a custom storage to be used.
```js
const memoized = memoizeFunction(fn, {
storage: {
store: {},
clear() {
this.store = {};
},
remove(key) {
delete this.store[key];
},
set(key, value) {
this.store[key] = value;
},
get(key) {
return this.store[key] || null;
},
},
});
``````js
class Storage {
store;constructor() {
this.store = {};
}clear() {
this.store = {};
}remove(key) {
delete this.store[key];
}get(key) {
return this.store[key] || null;
}set(key, value) {
this.store[key] = value;
}
}const memoized = memoizeFunction(fn, {
storage: new Storage(),
});
```The custom cache can be a class or an object implementing the following methods:
- `get`
- `set`
- `clear`
- `remove`### Custom cache key generator
To use a custom cache key generator:
```js
const generateCacheKey = (...args) =>
"my_custom_key_for_each_function_argument";const memoized = memoizeFunction(fn, {
generateCacheKey,
});
```