Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
typescript-memoize
Advanced tools
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.
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);
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 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 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.
A memoize decorator for Typescript.
npm install --save typescript-memoize
@Memoize(hashFunction?: (...args: any[]) => any)
You can use it in four ways:
get
accessor,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.
get
accessor, or a method which takes no parametersThese 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,MemoizeExpiring} from 'typescript-memoize';
class SimpleFoo {
// Memoize a method without parameters
@Memoize()
public getAllTheData() {
// do some expensive operation to get data
return data;
}
// Memoize a method and expire the value after some time in milliseconds
@MemoizeExpiring(5000)
public getDataForSomeTime() {
// do some expensive operation to get data
return data;
}
// Memoize a getter
@Memoize()
public get someValue() {
// do some expensive operation to calculate value
return value;
}
}
And then we call them from somewhere else in our code:
let simpleFoo = new SimpleFoo();
// Memoizes a calculated value and returns it:
let methodVal1 = simpleFoo.getAllTheData();
// Returns memoized value
let methodVal2 = simpleFoo.getAllTheData();
// Memoizes (lazy-loads) a calculated value and returns it:
let getterVal1 = simpleFoo.someValue;
// Returns memoized value
let getterVal2 = simpleFoo.someValue;
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 a method without parameters (just like the first example)
@Memoize()
public getAllTheData() {
// do some expensive operation to get data
return data;
}
// Memoize a method with one parameter
@Memoize()
public getSomeOfTheData(id: number) {
let allTheData = this.getAllTheData(); // if you want to!
// do some expensive operation to get data
return data;
}
// Memoize a method with multiple parameters
// Only the first parameter will be used for memoization
@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();
// Returns calculated value and memoizes it:
let oneParam1 = complicatedFoo.getSomeOfTheData();
// Returns memoized value
let oneParam2 = complicatedFoo.getSomeOfTheData();
// Memoizes a calculated value and returns it:
// 'Hello, Darryl! Welcome to Earth'
let greeterVal1 = complicatedFoo.getGreeting('Darryl', 'Earth');
// Ignores the second parameter, and returns memoized value
// 'Hello, Darryl! Welcome to Earth'
let greeterVal2 = complicatedFoo.getGreeting('Darryl', 'Mars');
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 a method with multiple parameters
// Memoize will remember values based on keys like: 'name;planet'
@Memoize((name: string, planet: string) => {
return name + ';' + planet;
})
public getBetterGreeting(name: string, planet: string) {
return 'Hello, ' + name + '! Welcome to ' + planet;
}
// Memoize based on some other logic
@Memoize(() => {
return new Date();
})
public memoryLeak(greeting: string) {
return greeting + '!!!!!';
}
// Memoize also accepts parameters via a single object argument
@Memoize({
expiring: 10000, // milliseconds
hashFunction: (name: string, planet: string) => {
return name + ';' + planet;
}
})
public getSameBetterGreeting(name: string, planet: string) {
return 'Hello, ' + name + '! Welcome to ' + planet;
}
}
We call these methods from somewhere else in our code. By now you should be getting the idea:
let moreComplicatedFoo = new MoreComplicatedFoo();
// 'Hello, Darryl! Welcome to Earth'
let greeterVal1 = moreComplicatedFoo.getBetterGreeting('Darryl', 'Earth');
// 'Hello, Darryl! Welcome to Mars'
let greeterVal2 = moreComplicatedFoo.getBetterGreeting('Darryl', 'Mars');
// Fill up the computer with useless greetings:
let greeting = moreComplicatedFoo.memoryLeak('Hello');
Passing an array with one or more "tag" strings these will allow you to later clear the cache of results associated with methods or the get
accessors using the clear()
function.
The clear()
function also requires an array of "tag" strings.
import {Memoize} from 'typescript-memoize';
class ClearableFoo {
// Memoize accepts tags
@Memoize({ tags: ["foo", "bar"] })
public getClearableGreeting(name: string, planet: string) {
return 'Hello, ' + name + '! Welcome to ' + planet;
}
// Memoize accepts tags
@Memoize({ tags: ["bar"] })
public getClearableSum(a: number, b: number) {
return a + b;
}
}
We call these methods from somewhere else in our code.
import {clear} from 'typescript-memoize';
let clearableFoo = new ClearableFoo();
// 'Hello, Darryl! Welcome to Earth'
let greeterVal1 = clearableFoo.getClearableGreeting('Darryl', 'Earth');
// Ignores the second parameter, and returns memoized value
// 'Hello, Darryl! Welcome to Earth'
let greeterVal2 = clearableFoo.getClearableGreeting('Darryl', 'Mars');
// '3'
let sum1 = clearableFoo.getClearableSum(2, 1);
// Ignores the second parameter, and returns memoized value
// '3'
let sum2 = clearableFoo.getClearableSum(2, 2);
clear(["foo"]);
// The memoized values are cleared, return a new value
// 'Hello, Darryl! Welcome to Mars'
let greeterVal3 = clearableFoo.getClearableGreeting('Darryl', 'Mars');
// The memoized value is not associated with 'foo' tag, returns memoized value
// '3'
let sum3 = clearableFoo.getClearableSum(2, 2);
clear(["bar"]);
// The memoized values are cleared, return a new value
// 'Hello, Darryl! Welcome to Earth'
let greeterVal4 = clearableFoo.getClearableGreeting('Darryl', 'Earth');
// The memoized values are cleared, return a new value
// '4'
let sum4 = clearableFoo.getClearableSum(2, 2);
FAQs
Memoize decorator for Typescript
We found that typescript-memoize 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
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.