From 1256e1c6aa1bddee2e897ed93d7d3551505ef008 Mon Sep 17 00:00:00 2001 From: Mitchell Hamilton Date: Thu, 1 Apr 2021 05:21:59 +1000 Subject: [PATCH] Memoize Node.isNodeList and Editor.isEditor (#4072) * Memoize Node.isNodeList * Memoize Editor.isEditor --- packages/slate/src/interfaces/editor.ts | 13 ++++++++++--- packages/slate/src/interfaces/node.ts | 13 ++++++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/slate/src/interfaces/editor.ts b/packages/slate/src/interfaces/editor.ts index 8b03bd7c9..5cc811c35 100755 --- a/packages/slate/src/interfaces/editor.ts +++ b/packages/slate/src/interfaces/editor.ts @@ -272,6 +272,8 @@ export interface EditorInterface { withoutNormalizing: (editor: Editor, fn: () => void) => void } +const IS_EDITOR_CACHE = new WeakMap() + export const Editor: EditorInterface = { /** * Get the ancestor above a location in the document. @@ -549,8 +551,12 @@ export const Editor: EditorInterface = { */ isEditor(value: any): value is Editor { - return ( - isPlainObject(value) && + if (!isPlainObject(value)) return false + const cachedIsEditor = IS_EDITOR_CACHE.get(value) + if (cachedIsEditor !== undefined) { + return cachedIsEditor + } + const isEditor = typeof value.addMark === 'function' && typeof value.apply === 'function' && typeof value.deleteBackward === 'function' && @@ -569,7 +575,8 @@ export const Editor: EditorInterface = { (value.selection === null || Range.isRange(value.selection)) && Node.isNodeList(value.children) && Operation.isOperationList(value.operations) - ) + IS_EDITOR_CACHE.set(value, isEditor) + return isEditor }, /** diff --git a/packages/slate/src/interfaces/node.ts b/packages/slate/src/interfaces/node.ts index 4e8b25e9c..e12a3a764 100755 --- a/packages/slate/src/interfaces/node.ts +++ b/packages/slate/src/interfaces/node.ts @@ -86,6 +86,8 @@ export interface NodeInterface { ) => Generator, void, undefined> } +const IS_NODE_LIST_CACHE = new WeakMap() + export const Node: NodeInterface = { /** * Get the node at a specific path, asserting that it's an ancestor node. @@ -384,7 +386,16 @@ export const Node: NodeInterface = { */ isNodeList(value: any): value is Node[] { - return Array.isArray(value) && value.every(val => Node.isNode(val)) + if (!Array.isArray(value)) { + return false + } + const cachedResult = IS_NODE_LIST_CACHE.get(value) + if (cachedResult !== undefined) { + return cachedResult + } + const isNodeList = value.every(val => Node.isNode(val)) + IS_NODE_LIST_CACHE.set(value, isNodeList) + return isNodeList }, /**