Skip to content

Commit 1e53717

Browse files
committed
Use WeakMap and fast path in isDraftable
1 parent 8e8396c commit 1e53717

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

src/utils/common.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,29 @@ export function isDraft(value: any): boolean {
2020
return !!value && !!value[DRAFT_STATE]
2121
}
2222

23+
const isDraftableCache = new WeakMap<object, boolean>()
2324
/** Returns true if the given value can be drafted by Immer */
2425
/*#__PURE__*/
2526
export function isDraftable(value: any): boolean {
26-
if (!value) return false
27-
return (
27+
// Fast path: primitives are never draftable
28+
if (!value || typeof value !== "object") return false
29+
30+
// Now safe to check cache since we know value is an object
31+
if (isDraftableCache.has(value)) {
32+
return isDraftableCache.get(value)!
33+
}
34+
35+
const result =
2836
isPlainObject(value) ||
2937
Array.isArray(value) ||
3038
!!value[DRAFTABLE] ||
3139
!!value.constructor?.[DRAFTABLE] ||
3240
isMap(value) ||
3341
isSet(value)
34-
)
42+
43+
// Safe to cache since value is an object
44+
isDraftableCache.set(value, result)
45+
return result
3546
}
3647

3748
const objectCtorString = Object.prototype.constructor.toString()

0 commit comments

Comments
 (0)