0.1.3 • Published 5 years ago

memoizor v0.1.3

Weekly downloads
2
License
MIT
Repository
github
Last release
5 years ago

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