What is typescript-memoize?
The `typescript-memoize` package provides decorators for memoizing methods in TypeScript. Memoization is a technique used to speed up function calls by caching the results of expensive function calls and returning the cached result when the same inputs occur again.
What are typescript-memoize's main functionalities?
Basic Memoization
This feature allows you to memoize a method so that the result is cached based on the input parameters. The second call with the same input will return the cached result without recomputing.
class Example {
@Memoize()
computeExpensiveValue(input: number): number {
console.log('Computing...');
return input * 2; // Simulate an expensive computation
}
}
const example = new Example();
console.log(example.computeExpensiveValue(5)); // Computing... 10
console.log(example.computeExpensiveValue(5)); // 10 (cached result)
Custom Cache Key
This feature allows you to specify a custom cache key for the memoization. This can be useful if you need more control over how the cache keys are generated.
class Example {
@Memoize((input: number) => `key-${input}`)
computeExpensiveValue(input: number): number {
console.log('Computing...');
return input * 2; // Simulate an expensive computation
}
}
const example = new Example();
console.log(example.computeExpensiveValue(5)); // Computing... 10
console.log(example.computeExpensiveValue(5)); // 10 (cached result)
Expiration Time
This feature allows you to set a time-to-live (TTL) for the cached result. After the TTL expires, the cached result will be invalidated, and the method will be recomputed.
class Example {
@Memoize({ ttl: 5000 })
computeExpensiveValue(input: number): number {
console.log('Computing...');
return input * 2; // Simulate an expensive computation
}
}
const example = new Example();
console.log(example.computeExpensiveValue(5)); // Computing... 10
setTimeout(() => {
console.log(example.computeExpensiveValue(5)); // Computing... 10 (cache expired)
}, 6000);
Other packages similar to typescript-memoize
lodash
Lodash is a popular utility library that provides a wide range of functions, including memoization. The `_.memoize` function in Lodash can be used to memoize functions, but it does not provide decorators out of the box. Lodash is more general-purpose and includes many other utilities beyond memoization.
memoizee
Memoizee is a dedicated memoization library for JavaScript. It offers a rich set of features for memoizing functions, including support for custom cache keys, expiration times, and more. Unlike `typescript-memoize`, it does not provide decorators specifically for TypeScript.
moize
Moize is another memoization library that offers a wide range of configuration options, including custom cache keys, expiration times, and more. It is designed to be highly configurable and performant. Like `memoizee`, it does not provide TypeScript decorators but can be used in TypeScript projects.
typescript-memoize
A memoize decorator for Typescript.
Installation
npm install --save typescript-memoize
Usage:
@Memoize(hashFunction?: (...args: any[]) => any)
You can use it in four ways:
- Memoize a
get
accessor, - Memoize a method which takes no parameters,
- Memoize a method which varies based on its first parameter only,
- Memoize a method which varies based on some combination of parameters
You can call memoized methods within the same class, too. This could be useful if you want to memoize the return value for an entire data set, and also a filtered or mapped version of that same set.
Memoize a get
accessor, or a method which takes no parameters
These both work the same way. Subsequent calls to a memoized method without parameters, or to a get
accessor, always return the same value.
I generally consider it an anti-pattern for a call to a get
accessor to trigger an expensive operation. Simply adding Memoize()
to a get
allows for seamless lazy-loading.
import {Memoize} from 'typescript-memoize';
class SimpleFoo {
@Memoize()
public getAllTheData() {
return data;
}
@Memoize()
public get someValue() {
return value;
}
}
And then we call them from somewhere else in our code:
let simpleFoo = new SimpleFoo();
let methodVal1 = simpleFoo.getAllTheData();
let methodVal2 = simpleFoo.getAllTheData();
let getterVal1 = simpleFoo.someValue;
let getterVal2 = simpleFoo.someValue;
Memoize a method which varies based on its first parameter only
Subsequent calls to this style of memoized method will always return the same value.
I'm not really sure why anyone would use this approach to memoize a method with more than one parameter, but it's possible.
import {Memoize} from 'typescript-memoize';
class ComplicatedFoo {
@Memoize()
public getAllTheData() {
return data;
}
@Memoize()
public getSomeOfTheData(id: number) {
let allTheData = this.getAllTheData();
return data;
}
@Memoize()
public getGreeting(name: string, planet: string) {
return 'Hello, ' + name + '! Welcome to ' + planet;
}
}
We call these methods from somewhere else in our code:
let complicatedFoo = new ComplicatedFoo();
let oneParam1 = complicatedFoo.getSomeOfTheData();
let oneParam2 = complicatedFoo.getSomeOfTheData();
let greeterVal1 = complicatedFoo.getGreeting('Darryl', 'Earth');
let greeterVal2 = complicatedFoo.getGreeting('Darryl', 'Mars');
Memoize a method which varies based on some combination of parameters
Pass in a hashFunction
which takes the same parameters as your target method, to memoize values based on all parameters, or some other custom logic
import {Memoize} from 'typescript-memoize';
class MoreComplicatedFoo {
@Memoize((name: string, planet: string) => {
return name + ';' + string;
})
public getBetterGreeting(name: string, planet: string) {
return 'Hello, ' + name + '! Welcome to ' + planet;
}
@Memoize(() => {
return new Date();
})
public memoryLeak(greeting: string) {
return greeting + '!!!!!';
}
}
We call these methods from somewhere else in our code. By now you should be getting the idea:
let moreComplicatedFoo = new MoreComplicatedFoo();
let greeterVal1 = moreComplicatedFoo.getBetterGreeting('Darryl', 'Earth');
let greeeterVal2 = moreComplicatedFoo.getBetterGreeting('Darryl', 'Mars');
let greeting = moreComplicatedFoo.memoryLeak('Hello');