1.3.3 • Published 5 years ago

@xornot/memo v1.3.3

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

xornot.io memo

A very naive memoizer that only compares arguments and receiver (this) by reference.

import {memo} from "@xornot/memo";

function myFunction(...args: any[]): void { /* ... */ }

const memoized = memo(myFunction);
const options = {
  foo: "foo"
};

memoized("a", options); // cache miss (first call)
memoized("a", options); // cache hit
memoized("b", options); // cache miss (argument change)
options.foo = "bar";
memoized("b", options); // cache hit (arguments compared by reference, so options.foo change not detected)
memoized("a", options); // cache miss (cache depth 1 by default, only caches the last call)

If you only want to cache results for a limited amount of time, use the ttl option.

const memoized = memo(() => { /* ... */ }, {ttl: 1000});
memoized(); // cache miss (first call)
memoized(); // cache hit (ttl hasn't expired)
setTimeout(memoized, 2000); // cache miss (ttl has expired).

If you want to cache results for more than just the last argument set, then set the cache depth to a number or Infinity.

const memoized = memo((str: string) => { /* ... */ }, {depth: 2});
memoized("a"); // cache miss (first call with "a")
memoized("b"); // cache miss (first call with "b")
memoized("c"); // cache miss (first call with "c")
memoized("c"); // cache hit
memoized("b"); // cache hit
memoized("a"); // cache miss ("a" was evicted by "c")
memoized("a"); // cache hit
memoized("b"); // cache miss ("b" was evicted by "a")

If you have a function which takes complex arguments like an options map, then create a backing function that takes a flattened set of parameters and memoize that.

interface IOptions {
  foo: string;
  bar: string;
}

const acceptOptions = ({foo, bar}: IOptions) = acceptOptionsMemo(foo, bar);
const acceptOptionsMemo = memo((foo: string, bar: string) => { /* ... */ });

If you want to reset the memoized function so that all cached values are forgotten, use the resetMemo() function.

import {memo, resetMemo} from "memo";

const memoized = memo(() => { /* ... */ });

memoized(); // cache miss
memoized(); // cache hit
resetMemo(memoized);
memoized(); // cache miss

If you want to register callbacks on cache hit and miss, use the onHit and onMiss options.

const memoized = memo(() => { /* ... */ }, {
  onHit: (args, value) => {
    // Called when a cached value is used.
  },
  onMiss: (args, value) => {
    // Called when a cached value is not available and a new value is created and added to the cache.
  }
})
1.3.3

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.2

5 years ago

1.2.1

5 years ago

1.2.0

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago