From 909ffccafbeea926e9f0589af7d9837d3093ac11 Mon Sep 17 00:00:00 2001 From: Cole Lawrence Date: Wed, 27 Apr 2022 16:21:51 -0400 Subject: [PATCH] refactor: Improve identifiers in pointer.ts + use Map over object (#134) Co-authored-by: Elliot --- packages/dataverse/src/pointer.ts | 44 ++++++++++++++++++------------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/packages/dataverse/src/pointer.ts b/packages/dataverse/src/pointer.ts index 39baeae..d914bb3 100644 --- a/packages/dataverse/src/pointer.ts +++ b/packages/dataverse/src/pointer.ts @@ -7,6 +7,9 @@ type PointerMeta = { path: (string | number)[] } +/** We are using an empty object as a WeakMap key for storing pointer meta data */ +type WeakPointerKey = {} + export type UnindexableTypesForPointer = | number | string @@ -20,7 +23,11 @@ export type UnindexablePointer = { [K in $IntentionalAny]: Pointer } -const pointerMetaWeakMap = new WeakMap<{}, PointerMeta>() +const pointerMetaWeakMap = new WeakMap() +const cachedSubPathPointersWeakMap = new WeakMap< + WeakPointerKey, + Map> +>() /** * A wrapper type for the type a `Pointer` points to. @@ -64,27 +71,26 @@ export type Pointer = PointerType & const pointerMetaSymbol = Symbol('pointerMeta') -const cachedSubPointersWeakMap = new WeakMap< - {}, - Record> ->() +const proxyHandler = { + get( + pointerKey: WeakPointerKey, + prop: string | typeof pointerMetaSymbol, + ): $IntentionalAny { + if (prop === pointerMetaSymbol) return pointerMetaWeakMap.get(pointerKey)! -const handler = { - get(obj: {}, prop: string | typeof pointerMetaSymbol): $IntentionalAny { - if (prop === pointerMetaSymbol) return pointerMetaWeakMap.get(obj)! - - let subs = cachedSubPointersWeakMap.get(obj) - if (!subs) { - subs = {} - cachedSubPointersWeakMap.set(obj, subs) + let subPathPointers = cachedSubPathPointersWeakMap.get(pointerKey) + if (!subPathPointers) { + subPathPointers = new Map() + cachedSubPathPointersWeakMap.set(pointerKey, subPathPointers) } - if (subs[prop]) return subs[prop] + const existing = subPathPointers.get(prop) + if (existing !== undefined) return existing - const meta = pointerMetaWeakMap.get(obj)! + const meta = pointerMetaWeakMap.get(pointerKey)! const subPointer = pointer({root: meta.root, path: [...meta.path, prop]}) - subs[prop] = subPointer + subPathPointers.set(prop, subPointer) return subPointer }, } @@ -158,9 +164,9 @@ function pointer(args: {root: {}; path?: Array}) { root: args.root as $IntentionalAny, path: args.path ?? [], } - const hiddenObj = {} - pointerMetaWeakMap.set(hiddenObj, meta) - return new Proxy(hiddenObj, handler) as Pointer + const pointerKey: WeakPointerKey = {} + pointerMetaWeakMap.set(pointerKey, meta) + return new Proxy(pointerKey, proxyHandler) as Pointer } export default pointer