From b5c8f6407b74466ed0d2989000458cb59239e9af Mon Sep 17 00:00:00 2001 From: Arda TANRIKULU Date: Mon, 6 Feb 2023 15:45:29 +0300 Subject: [PATCH] Introduce `memoize2of5` and fix `memoize2of4` --- .changeset/sweet-socks-clap.md | 5 +++++ packages/utils/src/memoize.ts | 25 ++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 .changeset/sweet-socks-clap.md diff --git a/.changeset/sweet-socks-clap.md b/.changeset/sweet-socks-clap.md new file mode 100644 index 00000000000..1634a0083d2 --- /dev/null +++ b/.changeset/sweet-socks-clap.md @@ -0,0 +1,5 @@ +--- +'@graphql-tools/utils': patch +--- + +Do not use a global `WeakMap` for `memoize2of4`, and introduce `memoize2of5` diff --git a/packages/utils/src/memoize.ts b/packages/utils/src/memoize.ts index 7f68a4133d0..83e60118a52 100644 --- a/packages/utils/src/memoize.ts +++ b/packages/utils/src/memoize.ts @@ -178,8 +178,8 @@ export function memoize5, WeakMap, any>> = new WeakMap(); export function memoize2of4 any>(fn: F): F { + const memoize2of4cache: WeakMap, WeakMap, any>> = new WeakMap(); return function memoized(a1: any, a2: any, a3: any, a4: any): any { let cache2 = memoize2of4cache.get(a1); if (!cache2) { @@ -200,3 +200,26 @@ export function memoize2of4 an return cachedValue; } as F; } + +export function memoize2of5 any>(fn: F): F { + const memoize2of4cache: WeakMap, WeakMap, 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; +}