Security News
pnpm 10.0.0 Blocks Lifecycle Scripts by Default
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
memoize-cache-decorator
Advanced tools
Cache the result of a method or getter for better performance. Supports timeout and clearing the cache.
Add the memoize decorator to your class methods to have the results cached for future calls.
This is an easy, clean and reliable way to prevent repeating unnecessary resource intensive tasks and improve the performance of your code.
Examples of resource intensive tasks that can be cached are: heavy calculations, network requests, file system operations and database operations.
With support for:
Since TypeScript decorators are used, the source has to be TypeScript. Also, decorators can only be used for class methods and getters. Plain JavaScript decorators are planned for the future.
npm install --save-dev memoize-cache-decorator
class Example {
@memoize()
myFunction() {
// …
}
}
Simple example:
import { memoize } from "memoize-cache-decorator";
class Example {
@memoize()
myFunction() {
// Heavy function getting data from disk, database or a server
// For this example we return a random number
return Math.random();
}
}
const example = new Example();
// Instead of a different random number for each call, the first,
// cached number is returned each time.
console.log(example.myFunction());
//=> 0.7649863352328616
console.log(example.myFunction());
//=> 0.7649863352328616
console.log(example.myFunction());
//=> 0.7649863352328616
In practice, the function would probably do a fetch, read a file or do a database call. Here's another, more realistic example:
import { memoize } from "memoize-cache-decorator";
class Example {
@memoize({ ttl: 5 * 60 * 1000 })
async getData(path: string) {
try {
const response = await fetch(path, {
headers: {
Accept: "application/json",
},
});
return response.json();
} catch (error) {
console.error(
`While fetching ${path}, the following error occured`,
error
);
return error;
}
}
}
const example = new Example();
const data = await example.getData("/path-to-data");
Now, every time getData
is called with this path, it returns the data without
fetching it over the network every time.
It will do a fetch over the network again after 5 minutes or when clearFunction(example.getData)
is called.
Memoize the class method or getter below it.
Config
interface Config {
resolver?: (...args: any[]) => string | number;
ttl?: number;
}
Function to convert function arguments to a unique key.
Without a resolver
function, the arguments are converted to a key with json-stringify-safe
,
a save version of JSON stringify.
This works fine when the arguments are primitives like strings, numbers and booleans.
This is undesirable when passing in objects with irrelevant data, like DOM elements.
Use resolver
to provide a function to calculate a unique key yourself.
Example:
import { memoize } from "memoize-cache-decorator";
class Example {
@memoize({ resolver: (el) => el.id })
myFunction(el) {
// el is some complex object
return fetch(`/rest/example/${el.id}`);
}
}
With ttl (time to live), the cache will never live longer than the given number of milliseconds.
import { memoize } from "memoize-cache-decorator";
class Example {
// The result is cached for at most 10 minutes
@memoize({ ttl: 10 * 60 * 1000 })
getComments() {
return fetch(`/rest/example/comments`);
}
}
Clears the cache belonging to a memoized function for a specific instance and specific arguments.
Call clear
with as arguments the instance, memoized function and memoized function arguments.
import { memoize, clear } from "memoize-cache-decorator";
class Example {
@memoize()
getDirection(direction: string) {
return fetch(`/rest/example/direction/${direction}`);
}
southUpdated() {
// The next time getComments("south") is called in this instance, comments will
// be fetched from the server again. But only for this instance.
clear(this, this.getDirection, "south");
}
}
Clears all caches belonging to a memoized function. All caches are cleared for the given function for all instances and for all arguments.
Call clearFunction
with as argument the memoized function.
import { memoize, clearFunction } from "memoize-cache-decorator";
class Example {
@memoize()
getComments() {
return fetch(`/rest/example/comments`);
}
commentsUpdated() {
// The next time getComments() is called, comments will
// be fetched from the server again.
clearFunction(this.getComments);
}
}
npm test
MIT © 2023 Edwin Martin
FAQs
Cache the result of a method or getter for better performance. Supports timeout and clearing the cache.
We found that memoize-cache-decorator demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
pnpm 10 blocks lifecycle scripts by default to improve security, addressing supply chain attack risks but sparking debate over compatibility and workflow changes.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.