1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-04-20 05:11:53 +02:00

Memoize Node.isNodeList and Editor.isEditor (#4072)

* Memoize Node.isNodeList

* Memoize Editor.isEditor
This commit is contained in:
Mitchell Hamilton 2021-04-01 05:21:59 +10:00 committed by GitHub
parent e46779dbd9
commit 1256e1c6aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 4 deletions

View File

@ -272,6 +272,8 @@ export interface EditorInterface {
withoutNormalizing: (editor: Editor, fn: () => void) => void
}
const IS_EDITOR_CACHE = new WeakMap<object, boolean>()
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
},
/**

View File

@ -86,6 +86,8 @@ export interface NodeInterface {
) => Generator<NodeEntry<Text>, void, undefined>
}
const IS_NODE_LIST_CACHE = new WeakMap<any[], boolean>()
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
},
/**