memoizor
TypeScript icon, indicating that this package has built-in type declarations

0.1.3 • Public • Published

Memoizor

Memoization implementation for TypeScript

Installation

npm i --save memoizor

Usage

Inline Functions

You can use memoize method for inline functions:

import { memoize } from "memoizor";
 
const fact = (n: number): number => {
    if (n > 1) {
        return n * fact(n - 1);
    }
 
    return 1;
};
 
const memoizedFact = memoize(fact);
 
console.log(memoizedFact(10));

Class Methods

Also you can use it for class methods:

import { memoize } from "memoizor";
 
class Fact {
    @memoize()
    fact(n: number): number {
        if (n > 1) {
            return n * this.fact(n - 1);
        }
 
        return 1;
    }
}
 
let fact = new Fact();
 
console.log(fact.fact(10));

Async Functions

You can memoize async function using an option named type:

import { memoize } from "memoizor";
 
class MyClass {
    @memoize({
        type: "async"
    })
    async myFn(args: any[]): any {
        ...
    }
}
 
let my = new MyClass();
 
console.log(await my.myFn(10));

Generic Hash Function

You can use your own cache key generator method using an option named hasher:

import { memoize } from "memoizor";
 
class Fact {
    @memoize({
        hasher: (...args: any[]): any => {
            return String(args[0]);
        }
    })
    fact(n: number): number {
        if (n > 1) {
            return n * this.fact(n - 1);
        }
 
        return 1;
    }
}
 
let fact = new Fact();
 
console.log(fact.fact(10));

Contributions

License

MIT

Package Sidebar

Install

npm i memoizor

Weekly Downloads

3

Version

0.1.3

License

MIT

Unpacked Size

234 kB

Total Files

14

Last publish

Collaborators

  • koliber