memoize-one
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
"memoize-one" is a memoization library designed for JavaScript applications. It aims to provide a good performance boost to an application by caching the result of the most recent function invocation. This characteristic sets it apart from other memoization libraries: "memoize-one" only remembers the latest arguments and result, and does not use cache busting mechanisms like maxAge
, maxSize
, or exclusions
. If the memoized function is called again with the same arguments as the last time, "memoize-one" will return the previously cached result, resulting in a potential performance boost. The library also provides additional features, such as ability to clear the cache and custom equality function support.
To use "memoize-one", first install the package via npm or yarn.
# npm
npm install memoize-one --save
# yarn
yarn add memoize-one
Then, you can import it into your JavaScript files and use it to memoize your functions. Here's an example:
import memoizeOne from 'memoize-one';
const expensiveFunction = (arg1, arg2) => {
// expensive computation here
.......
return result;
}
const memoizedExpensiveFunction = memoizeOne(expensiveFunction);
// Call the memoized function
var result1 = memoizedExpensiveFunction(arg1, arg2);
// if called again with the same arguments, memoized result will be returned
// improving the performance
var result2 = memoizedExpensiveFunction(arg1, arg2);
The library also allows you to use a custom equality function, which determines whether the new arguments are equivalent to previous ones. Here's an example, using the lodash.isequal
function:
import memoizeOne from 'memoize-one';
import isEqual from 'lodash.isequal';
const identity = (x) => x;
const memoized = memoizeOne(identity, isEqual);
The memoization cache can be manually cleared using the .clear()
function that is attached to memoized functions:
const memoizedExpensiveFunction = memoizeOne(expensiveFunction);
memoizedExpensiveFunction(arg1, arg2); // calculate result and cache it
memoizedExpensiveFunction.clear(); // clear the cache
For detailed documentation and additional usage examples of "memoize-one", you can check out the official GitHub repo. The repository includes explanations of how the library handles different types of function arguments and contexts, customization of the equality function, handling function properties, and more. You will also find performance comparisons and information about code health.