Skip to content

Commit

Permalink
perf(formatWithCursor): Swap diff for faster-diff
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Macwright authored and tmcw committed Aug 8, 2018
1 parent 4fb2070 commit 43db237
Show file tree
Hide file tree
Showing 6 changed files with 405 additions and 29 deletions.
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -24,7 +24,6 @@
"cosmiconfig": "5.0.5",
"dashify": "0.2.2",
"dedent": "0.7.0",
"diff": "3.2.0",
"editorconfig": "0.15.0",
"editorconfig-to-prettier": "0.0.6",
"emoji-regex": "6.5.1",
Expand Down
30 changes: 10 additions & 20 deletions src/main/core.js
@@ -1,6 +1,6 @@
"use strict";

const diff = require("diff");
const diff = require("../utils/diff");

const normalizeOptions = require("./options").normalize;
const massageAST = require("./massage-ast");
Expand All @@ -16,8 +16,6 @@ const {

const UTF8BOM = 0xfeff;

const CURSOR = Symbol("cursor");

function guessLineEnding(text) {
const index = text.indexOf("\n");
if (index >= 0 && text.charAt(index - 1) === "\r") {
Expand Down Expand Up @@ -137,30 +135,22 @@ function coreFormat(text, opts, addAlignmentSize) {
}

// diff old and new cursor node texts, with a special cursor
// symbol inserted to find out where it moves to

const oldCursorNodeCharArray = oldCursorNodeText.split("");
oldCursorNodeCharArray.splice(
cursorOffsetRelativeToOldCursorNode,
0,
CURSOR
);

const newCursorNodeCharArray = newCursorNodeText.split("");
// character inserted to find out where it moves to
const oldCursorNodeTextWithMark =
oldCursorNodeText.substring(0, cursorOffsetRelativeToOldCursorNode) +
"\0" +
oldCursorNodeText.substring(cursorOffsetRelativeToOldCursorNode);

const cursorNodeDiff = diff.diffArrays(
oldCursorNodeCharArray,
newCursorNodeCharArray
);
const cursorNodeDiff = diff(oldCursorNodeTextWithMark, newCursorNodeText);

let cursorOffset = newCursorNodeStart;
for (const entry of cursorNodeDiff) {
if (entry.removed) {
if (entry.value.indexOf(CURSOR) > -1) {
if (entry[0] === -1) {
if (entry[1].indexOf("\0") > -1) {
break;
}
} else {
cursorOffset += entry.count;
cursorOffset += entry[1].length;
}
}

Expand Down

0 comments on commit 43db237

Please sign in to comment.