Skip to content

Commit

Permalink
Introduce memoize2of5 and fix memoize2of4
Browse files Browse the repository at this point in the history
  • Loading branch information
ardatan committed Feb 6, 2023
1 parent 85659bc commit b5c8f64
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/sweet-socks-clap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@graphql-tools/utils': patch
---

Do not use a global `WeakMap` for `memoize2of4`, and introduce `memoize2of5`
25 changes: 24 additions & 1 deletion packages/utils/src/memoize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,8 @@ export function memoize5<F extends (a1: any, a2: any, a3: any, a4: any, a5: any)
} as F;
}

const memoize2of4cache: WeakMap<Record<string, any>, WeakMap<Record<string, any>, any>> = new WeakMap();
export function memoize2of4<F extends (a1: any, a2: any, a3: any, a4: any) => any>(fn: F): F {
const memoize2of4cache: WeakMap<Record<string, any>, WeakMap<Record<string, any>, any>> = new WeakMap();
return function memoized(a1: any, a2: any, a3: any, a4: any): any {
let cache2 = memoize2of4cache.get(a1);
if (!cache2) {
Expand All @@ -200,3 +200,26 @@ export function memoize2of4<F extends (a1: any, a2: any, a3: any, a4: any) => an
return cachedValue;
} as F;
}

export function memoize2of5<F extends (a1: any, a2: any, a3: any, a4: any, a5: any) => any>(fn: F): F {
const memoize2of4cache: WeakMap<Record<string, any>, WeakMap<Record<string, any>, any>> = new WeakMap();
return function memoized(a1: any, a2: any, a3: any, a4: any, a5: any): any {
let cache2 = memoize2of4cache.get(a1);
if (!cache2) {
cache2 = new WeakMap();
memoize2of4cache.set(a1, cache2);
const newValue = fn(a1, a2, a3, a4, a5);
cache2.set(a2, newValue);
return newValue;
}

const cachedValue = cache2.get(a2);
if (cachedValue === undefined) {
const newValue = fn(a1, a2, a3, a4, a5);
cache2.set(a2, newValue);
return newValue;
}

return cachedValue;
} as F;
}

0 comments on commit b5c8f64

Please sign in to comment.