From 4d56d7dff3ae74934d08d5b92bc8c98c87ee05c4 Mon Sep 17 00:00:00 2001 From: David Himmelstrup Date: Sat, 14 Oct 2017 15:34:07 -0700 Subject: [PATCH] Change 'lookUpwardForInlineStyle' from O(n^2) to O(n). Summary: **Summary** The function 'lookUpwardForInlineStyle' repeatedly called 'getPreviousBlock' which has the complexity O(n). This tanks performance when creating a document with lots of empty lines. Simply holding down the enter key will quickly cause the frame rate to drop below 1fps. The fix is straightforward and, in my opinion, preferable to a while loop. **Test Plan** I did some manual testing. The code was able to correctly (and efficiently) find the correct style. Closes https://github.com/facebook/draft-js/pull/1429 Differential Revision: D6060417 fbshipit-source-id: 8a14af25f776ac5263747e2fc4bbb665884ad970 --- src/model/immutable/EditorState.js | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/model/immutable/EditorState.js b/src/model/immutable/EditorState.js index 1d83378..8f5f547 100644 --- a/src/model/immutable/EditorState.js +++ b/src/model/immutable/EditorState.js @@ -652,17 +652,15 @@ function lookUpwardForInlineStyle( content: ContentState, fromKey: string, ): DraftInlineStyle { - var previousBlock = content.getBlockBefore(fromKey); - var previousLength; - - while (previousBlock) { - previousLength = previousBlock.getLength(); - if (previousLength) { - return previousBlock.getInlineStyleAt(previousLength - 1); - } - previousBlock = content.getBlockBefore(previousBlock.getKey()); - } - + var lastNonEmpty = content.getBlockMap() + .reverse() + .skipUntil((_, k) => k === fromKey) + .skip(1) + .skipUntil((block, _) => block.getLength()) + .first(); + + if (lastNonEmpty) + return lastNonEmpty.getInlineStyleAt(lastNonEmpty.getLength() - 1); return OrderedSet(); }