npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

memoize-cache-decorator

v2.0.0

Published

Cache the result of a method or getter for better performance. Supports timeout and clearing the cache.

Downloads

168

Readme

Test Coverage Status Quality Gate Status Socket Badge CodeFactor npm version GitHub

memoize-cache-decorator

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:

  • Both Node.js and browsers
  • Methods and getter functions
  • Async functions
  • Static functions
  • Cache expiration
  • Clearing the cache on two levels
  • Custom resolver function
  • TypeScript

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.

Installation

npm install --save-dev memoize-cache-decorator

Usage

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.

API

@memoize(config)

Memoize the class method or getter below it.

Type: [optional] Config

interface Config {
	resolver?: (...args: any[]) => string | number;
	ttl?: number;
}
resolver [optional] function

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}`);
	}
}
ttl [optional] number

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`);
	}
}

clear(instance, fn, arguments)

instance object
fn function
arguments [optional] arguments of fn

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");
	}
}

clearFunction(fn)

fn function

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);
	}
}

Tests

npm test

Related

License

MIT © 2023 Edwin Martin