A simple Memoize helper, with TypeScript decorator support!
npm install @github/memoizeThis is a package which provides a memoize function, as well as a TypeScript
decorator which will memoize a class method.
``typescript
import memoize from '@github/memoize'
const fn = memoize(function doExpensiveStuff() {
// Here's where you do expensive stuff!
})
const other = memoize(function doExpensiveStuff() {}, {
cache: new Map(), // pass your own cache implementation
hash: JSON.stringify // pass your own hashing implementation
})
`
#### Options:
- hash?: (...args: A) => unknownJSON.stringify
Provides a single value to use as the Key for the memoization.
Defaults to (ish).cache?: Map
-
The Cache implementation to provide. Must be a Map or Map-alike. Defaults to a Map.
Useful for replacing the cache with an LRU cache or similar.
This package also includes a decorator module which can be used to provide TypeScript Decorator annotations to functions.
Here's an example, showing what you need to do:
`typescript/decorator
import memoize from '@github/memoize/decorator'
// ^ note: add to the import to get decorators
class MyClass {
@memoize() // Memoize the method below
doThings() {
}
}
const cache = new Map()
class MyClass {
@memoize({ cache }) // Pass options just like the memoize function
doThings() {
}
}
`
Many memoize implementations exist. This one provides all of the utility we need at GitHub and nothing more. We've used a few various implementations in the past, here are some good ones:
- memoize
- mem
- lodash.memoize
```
npm install
npm test
Distributed under the MIT license. See LICENSE for details.