|
| 1 | +#memoize |
| 2 | + |
| 3 | +This is a package which provides a[`memoize`](https://en.wikipedia.org/wiki/Memoization) function, as well as a TypeScript |
| 4 | +decorator which will[memoize](https://en.wikipedia.org/wiki/Memoization) a class method. |
| 5 | + |
| 6 | +###Usage |
| 7 | + |
| 8 | +```typescript |
| 9 | +importmemoizefrom'@github/memoize' |
| 10 | + |
| 11 | +const fn=memoize(function doExpensiveStuff() { |
| 12 | +// Here's where you do expensive stuff! |
| 13 | +}) |
| 14 | + |
| 15 | +const other=memoize(function doExpensiveStuff() {}, { |
| 16 | + cache:newMap(),// pass your own cache implementation |
| 17 | + hash:JSON.stringify// pass your own hashing implementation |
| 18 | +}) |
| 19 | +``` |
| 20 | + |
| 21 | +####Options: |
| 22 | + |
| 23 | +-`hash?: (...args: A) => unknown` |
| 24 | + Provides a single value to use as the Key for the memoization. |
| 25 | + Defaults to`JSON.stringify` (ish). |
| 26 | +-`cache?: Map<unknown, R>` |
| 27 | + The Cache implementation to provide. Must be a Map or Map-alike. Defaults to a Map. |
| 28 | + Useful for replacing the cache with an LRU cache or similar. |
| 29 | + |
| 30 | +###TypeScript Decorators Support! |
| 31 | + |
| 32 | +This package also includes a decorator module which can be used to provide[TypeScript Decorator](https://www.typescriptlang.org/docs/handbook/decorators.html#decorators) annotations to functions. |
| 33 | + |
| 34 | +Here's an example, showing what you need to do: |
| 35 | + |
| 36 | +```typescript |
| 37 | +importmemoizefrom'@github/memoize/decorator' |
| 38 | +// ^ note: add `/decorator` to the import to get decorators |
| 39 | + |
| 40 | +classMyClass { |
| 41 | + @memoize()// Memoize the method below |
| 42 | + doThings() { |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +const cache=newMap() |
| 47 | +classMyClass { |
| 48 | + @memoize({cache })// Pass options just like the memoize function |
| 49 | + doThings() { |
| 50 | + } |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +###Why not just use package X? |
| 55 | + |
| 56 | +Many memoize implementations exist. This one provides all of the utility we need at[GitHub](https://github.com/github) and nothing more. We've used a few various implementations in the past, here are some good ones: |
| 57 | + |
| 58 | +-[memoize](https://www.npmjs.com/package/memoize) |
| 59 | +-[mem](https://www.npmjs.com/package/mem) |
| 60 | +-[lodash.memoize](https://www.npmjs.com/package/lodash.memoize) |