Skip to content

Commit

Permalink
Merge pull request #1 from github/feat-initial-implementation
Browse files Browse the repository at this point in the history
Initial Implementation
  • Loading branch information
keithamus authored Jul 8, 2020
2 parents e4e80c1 + 3e59dfd commit 0773247
Show file tree
Hide file tree
Showing 12 changed files with 2,962 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Node CI

on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js 14.x
uses: actions/setup-node@v1
with:
node-version: 14.x
- name: npm install, build, and test
run: |
npm install
npm run build --if-present
npm test
env:
CI: true

2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
dist/
1 change: 1 addition & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @github/web-systems-reviewers
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 GitHub, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
60 changes: 60 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# memoize

This is a package which provides a [`memoize`](https://en.wikipedia.org/wiki/Memoization) function, as well as a TypeScript
decorator which will [memoize](https://en.wikipedia.org/wiki/Memoization) a class method.

### Usage

```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) => unknown`
Provides a single value to use as the Key for the memoization.
Defaults to `JSON.stringify` (ish).
- `cache?: Map<unknown, R>`
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.

### TypeScript Decorators Support!

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.

Here's an example, showing what you need to do:

```typescript
import memoize from '@github/memoize/decorator'
// ^ note: add `/decorator` 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() {
}
}
```

### Why not just use package X?

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:

- [memoize](https://www.npmjs.com/package/memoize)
- [mem](https://www.npmjs.com/package/mem)
- [lodash.memoize](https://www.npmjs.com/package/lodash.memoize)
9 changes: 9 additions & 0 deletions decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import memo from './index.js'
import type {MemoizeOptions, MemoizableFunction} from './index.js'

export default function memoize<A extends unknown[], R, T>(memoizeOptions: MemoizeOptions<A, R> = {}) {
return (target: T, propertyKey: string | symbol, descriptor: PropertyDescriptor): void => {
descriptor.value = memo(descriptor.value as MemoizableFunction<A, R, T>, memoizeOptions)
Object.defineProperty(target, propertyKey, descriptor)
}
}
41 changes: 41 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
export interface MemoizeOptions<A extends unknown[], R> {
/**
* Provides a single value to use as the Key for the memoization.
* Defaults to `JSON.stringify` (ish).
*/
hash?: (...args: A) => unknown

/**
* 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.
*/
cache?: Map<unknown, R>
}

export type MemoizableFunction<A extends unknown[], R extends unknown, T extends unknown> = (this: T, ...args: A) => R

export function defaultHash(...args: unknown[]): string {
// JSON.stringify ellides `undefined` and function values by default. We do not want that.
return JSON.stringify(args, (_: unknown, v: unknown) => (typeof v === 'object' ? v : String(v)))
}

export default function memoize<A extends unknown[], R extends unknown, T extends unknown>(
fn: MemoizableFunction<A, R, T>,
opts: MemoizeOptions<A, R> = {}
): MemoizableFunction<A, R, T> {
const {hash = defaultHash, cache = new Map()} = opts
return function (this: T, ...args: A) {
const id = hash.apply(this, args)
if (cache.has(id)) return cache.get(id)
const result = fn.apply(this, args)
if (result instanceof Promise) {
// eslint-disable-next-line github/no-then
result.catch(error => {
cache.delete(id)
throw error
})
}
cache.set(id, result)
return result
}
}
Loading

0 comments on commit 0773247

Please sign in to comment.