Skip to content

Commit

Permalink
Merge pull request #12 from keithamus/patch-1
Browse files Browse the repository at this point in the history
allow for customising of the hash return type as `H`
  • Loading branch information
srt32 authored Apr 17, 2023
2 parents 5c2f4a3 + e6355fb commit a794f67
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
export interface MemoizeOptions<A extends unknown[], R> {
export interface MemoizeOptions<A extends unknown[], R, H = unknown> {
/**
* Provides a single value to use as the Key for the memoization.
* Defaults to `JSON.stringify` (ish).
*/
hash?: (...args: A) => unknown
hash?: (...args: A) => H

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

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

export function defaultHash(...args: unknown[]): string {
export function defaultHash<A extends unknown[], H extends unknown>(...args: A): H {
// 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)))
return JSON.stringify(args, (_: unknown, v: unknown) => (typeof v === 'object' ? v : String(v))) as H
}

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

0 comments on commit a794f67

Please sign in to comment.