1.2.0 • Published 4 years ago

trie-memoize v1.2.0

Weekly downloads
2,035
License
MIT
Repository
github
Last release
4 years ago

A memoization algorithm in which each function argument represents a new key in a mapping, creating a trie of caches - the depth of which defined by your setup. It is very quick with its O(n arguments) lookup performance and is memory-efficient, particularly when WeakMaps are used.

This memoization function only works for functions where the exact number of arguments is known and constant.

Quick Start

const m1 = memoize([{}], (v) => v.toUpperCase())
m1('foo') // FOO uncached
m1('foo') // FOO cached

const m2 = memoize([{}, Map], (v1, v2) => `${v1}-${v2}`)
m2('foo', 'bar') // foo-bar, uncached
m2('foo', 'bar') // foo-bar, cached

const m3 = memoize(
  [WeakMap, Map, WeakMap],
  (v1, v2, v3) =>
    `${JSON.stringify(v1)}-${JSON.stringify(v1)}-${JSON.stringify(v3)}`
)

const v1 = {}
const v2 = 'foo'
const v3 = {}
m3(v1, v2, v3) // {}-"foo"-{} uncached
m3(v1, v2, v3) // {}-"foo"-{} cached

API

memoize(caches, fn)

ArgumentTypeDescription
cachesCacheConstructor[]An array of plain objects or map-like constructors (Map, WeakMap, some custom map w/ get + set methods) used for caching each level of the tree. The first array element will be the cache for the first argument of the function, call, and so on. Therefore, the length of this array must be the same as the length of arguments your memoized function accepts, or at least as deep as you'd like to cache.
fn(...args: T) => UThe function you'd like to memoize

Types

CacheConstructor

export type CacheConstructor =
  | MapConstructor
  | WeakMapConstructor
  | MapLike
  | Record<any, any>

LICENSE

MIT

1.2.0

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.19

4 years ago

1.0.18

4 years ago

1.0.17

4 years ago

1.0.16

4 years ago

1.0.15

5 years ago

1.0.14

5 years ago

1.0.13

5 years ago

1.0.12

5 years ago

1.0.11

5 years ago

1.0.10

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

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