Skip to content

Commit 6748a47

Browse files
committed
Refactor the code
1 parent 3aef6d6 commit 6748a47

File tree

3 files changed

+65
-223
lines changed

3 files changed

+65
-223
lines changed

lib/sort-json-core.js

Lines changed: 46 additions & 191 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const sorter = require('./sort-json-utils');
21
const babylon = require('babylon');
32
const generate = require('@babel/generator');
43

@@ -28,166 +27,10 @@ function getAutoIndent(selectedText, indent) {
2827
return autoIndent;
2928
}
3029

31-
var MARK_START = String.fromCharCode(193);
32-
var MARK_END = String.fromCharCode(201);
33-
34-
function generateMark(number) {
35-
return `${MARK_START}${number}${MARK_END}`;
36-
}
37-
38-
function getMarkRegex() {
39-
return new RegExp(`${MARK_START}([0-9]+)${MARK_END}`, 'g');
40-
}
41-
42-
function getNeedReverseMarkRegex() {
43-
return new RegExp(`"${MARK_START}([0-9]+)${MARK_END}([^"]*)"`, 'g');
44-
}
45-
46-
function getReverseBackMarkRegex() {
47-
return new RegExp(`"([^"]*)${MARK_END}([0-9]+)${MARK_START}"`, 'g');
48-
}
49-
50-
function addMark(marks, value) {
51-
var length = marks.length;
52-
var mark = generateMark(length);
53-
marks.push(value);
54-
return mark;
55-
}
56-
57-
function decodeMark(sortedJsonText, marks) {
58-
return (
59-
sortedJsonText
60-
// replace the reverse mark
61-
.replace(getReverseBackMarkRegex(), (match, value, markIndex) => {
62-
return `"${marks[markIndex]}${value}"`;
63-
})
64-
// replace mark
65-
.replace(getMarkRegex(), (match, markIndex) => {
66-
return marks[markIndex];
67-
})
68-
);
69-
}
70-
71-
function objectStringToJson(objectString, marks, autoIndent) {
72-
var autoIndentString = new Array(autoIndent).fill(' ').join('');
73-
74-
var json = objectString
75-
// Add mark for \' and \"
76-
.replace(/\\(\"|\')/g, match => addMark(marks, match))
77-
// Add mark for "
78-
.replace(/\"/g, match => addMark(marks, match))
79-
// Add mark for end line comments
80-
.replace(
81-
/(\/\/.*)(\n|\t)\s*\}/g,
82-
(match, comments) => `${addMark(marks, `${comments}`)}}`
83-
)
84-
// Add mark for line comments
85-
.replace(/(\/\/.*)/g, comments =>
86-
addMark(marks, `${comments}\n${autoIndentString}`)
87-
)
88-
// Change the multiple lines to one line
89-
.replace(/\s*(\n|\t)\s*/g, '')
90-
// Replace the " with '
91-
// .replace(/"/g, `'`)
92-
// Add "" to all the keys and values
93-
.replace(/([^\{\}\[\]:,]+)/g, match => {
94-
var realMatch = match.trim();
95-
return realMatch ? `"${match.trim()}"` : realMatch;
96-
})
97-
// reverse mark if it is at the beginning of the line
98-
.replace(
99-
getNeedReverseMarkRegex(),
100-
(match, markIndex, value) =>
101-
`"${value}${MARK_END}${markIndex}${MARK_START}"`
102-
);
103-
104-
var es6ShortLandRegex = /([\{,]+)\s*("[^\{\}:,]+")\s*([\},]+)/g;
105-
var isEs6 = false;
106-
while (json.match(es6ShortLandRegex)) {
107-
// Change ES6 single value to be JSON
108-
json = json.replace(
109-
es6ShortLandRegex,
110-
(match, $1, $2, $3) => `${$1}${$2}:${$2}${$3}`
111-
);
112-
isEs6 = true;
113-
}
114-
115-
return {
116-
json,
117-
isEs6,
118-
};
119-
}
120-
121-
function jsonToObjectString(json, needTailingComma, autoIndent, isEs6) {
122-
var objectString = json
123-
// remove the "" to all the keys and values
124-
.replace(/"([^\{\}:,]+)"/g, (match, $1) => $1);
125-
126-
if (autoIndent) {
127-
var objectStringLines = objectString.split('\n');
128-
var autoIndentString = new Array(autoIndent).fill(' ').join('');
129-
130-
for (var i = 1; i < objectStringLines.length; i++) {
131-
objectStringLines[i] = autoIndentString + objectStringLines[i];
132-
}
133-
134-
objectString = objectStringLines.join('\n');
135-
}
136-
137-
if (needTailingComma) {
138-
var tailingCommaRegex = /([^\{:,\s\t\n]+)([\s\t\n]*[\]\}])/g;
139-
while (objectString.match(tailingCommaRegex)) {
140-
objectString = objectString.replace(
141-
tailingCommaRegex,
142-
(match, $1, $2) => `${$1},${$2}`
143-
);
144-
}
145-
}
146-
147-
if (isEs6) {
148-
console.log(`isEs6: ${isEs6}`);
149-
150-
objectString = objectString
151-
.split('\n')
152-
.map(line => {
153-
console.log(`line: ${line}`);
154-
155-
var keyValuePair = line.replace(/,[\s]*/, '').split(':');
156-
if (
157-
keyValuePair.length === 2 &&
158-
keyValuePair[0].trim() === keyValuePair[1].trim()
159-
) {
160-
console.log(`return: ${`${keyValuePair[0]},`}`);
161-
return `${keyValuePair[0]},`;
162-
} else {
163-
console.log(`origin return: ${line}`);
164-
return line;
165-
}
166-
})
167-
.join('\n');
168-
}
169-
170-
// replace the comma at the end
171-
objectString = objectString.replace(
172-
/(\/\/.*)(\n|\t)(\s*\})/g,
173-
(match, comments, $2, $3) => `${comments.replace(/,$/, '')}${$2}${$3}`
174-
);
175-
176-
return objectString;
177-
}
178-
17930
function checkIfNeedTailingComma(objectString) {
18031
return objectString.match(/,[\s\t\n]*\}/);
18132
}
18233

183-
function checkIsObjectText(selectedText) {
184-
return (
185-
selectedText.length > 2 &&
186-
selectedText[0] === '{' &&
187-
selectedText[selectedText.length - 1] === '}'
188-
);
189-
}
190-
19134
function addAutoIndent(text, autoIndent) {
19235
const autoIndentString = new Array(autoIndent).fill(' ').join('');
19336
const lines = text.split('\n');
@@ -200,32 +43,29 @@ function addAutoIndent(text, autoIndent) {
20043
].join('\n');
20144
}
20245

203-
function selectedTextToSortedText(
204-
selectedText,
205-
indent,
206-
jsonParser,
207-
sortOrder,
208-
sortOptions
209-
) {
210-
var needTailingComma = checkIfNeedTailingComma(selectedText);
211-
212-
var autoIndent = getAutoIndent(selectedText, indent);
46+
function addTaillingComma(sortedText, needTailingComma) {
47+
if (needTailingComma) {
48+
var tailingCommaRegex = /([^\{:,\s\t\n]+)([\s\t\n]*[\]\}])/g;
49+
while (sortedText.match(tailingCommaRegex)) {
50+
sortedText = sortedText.replace(
51+
tailingCommaRegex,
52+
(match, $1, $2) => `${$1},${$2}`
53+
);
54+
}
55+
}
21356

214-
const declarPrefix = 'const a = ';
215-
let code = `${declarPrefix}${selectedText}`;
57+
return sortedText;
58+
}
21659

217-
let ast;
60+
function swithCorrectIndent(sortedText, indent) {
61+
return sortedText.replace(/ /g, new Array(indent).fill(' ').join(''));
62+
}
21863

219-
try {
220-
ast = babylon.parse(code, {
221-
sourceType: 'module',
222-
plugins: ['objectRestSpread'],
223-
});
224-
} catch (e) {
225-
throw { message: 'Please make sure your selected text is a JS obejct!' };
226-
}
64+
function removeWrapper(sortedText, declarePrefix) {
65+
return sortedText.slice(declarePrefix.length).replace(/;$/, '');
66+
}
22767

228-
const object = ast.program.body[0].declarations[0].init;
68+
function sortObject(object, sortOrder) {
22969
object.properties = object.properties.sort((a, b) => {
23070
if (!a.key) {
23171
return 1;
@@ -247,23 +87,38 @@ function selectedTextToSortedText(
24787
if (sortOrder && sortOrder.indexOf('desc') >= 0) {
24888
object.properties = object.properties.reverse();
24989
}
90+
}
25091

251-
let sortedText = generate.default(ast, {}, code).code;
92+
function selectedTextToSortedText(selectedText, indent, sortOrder) {
93+
var needTailingComma = checkIfNeedTailingComma(selectedText);
25294

253-
sortedText = sortedText.replace(/ /g, new Array(indent).fill(' ').join(''));
254-
sortedText = sortedText.slice(declarPrefix.length, sortedText.length - 1);
255-
sortedText = addAutoIndent(sortedText, autoIndent);
95+
var autoIndent = getAutoIndent(selectedText, indent);
25696

257-
if (needTailingComma) {
258-
var tailingCommaRegex = /([^\{:,\s\t\n]+)([\s\t\n]*[\]\}])/g;
259-
while (sortedText.match(tailingCommaRegex)) {
260-
sortedText = sortedText.replace(
261-
tailingCommaRegex,
262-
(match, $1, $2) => `${$1},${$2}`
263-
);
264-
}
97+
const declarePrefix = 'const a = ';
98+
let code = `${declarePrefix}${selectedText}`;
99+
100+
let ast;
101+
102+
try {
103+
ast = babylon.parse(code, {
104+
sourceType: 'module',
105+
plugins: ['objectRestSpread'],
106+
});
107+
} catch (e) {
108+
throw { message: 'Please make sure your selected text is a JS obejct!' };
265109
}
266110

111+
let object = ast.program.body[0].declarations[0].init;
112+
113+
sortObject(object, sortOrder);
114+
115+
let sortedText = generate.default(ast, {}, code).code;
116+
117+
sortedText = swithCorrectIndent(sortedText, indent);
118+
sortedText = removeWrapper(sortedText, declarePrefix);
119+
sortedText = addAutoIndent(sortedText, autoIndent);
120+
sortedText = addTaillingComma(sortedText, needTailingComma);
121+
267122
return sortedText;
268123
}
269124

lib/sort-json.js

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
var vscode = require('vscode');
22
var sorterCore = require('./sort-json-core');
3-
var JSON5 = require('json5');
4-
5-
function getConfig() {
6-
return vscode.workspace.getConfiguration('sortJSON');
7-
}
83

94
function getSelection(textEditor, startLine, startPos, endLine, endPos) {
105
var selectedLines = [];
@@ -30,11 +25,11 @@ function findIndent(textEditor) {
3025

3126
function sortActiveSelection(comparator) {
3227
try {
33-
sortActiveSelectionInternal(JSON5, comparator);
28+
sortActiveSelectionInternal(comparator);
3429
return true;
3530
} catch (e) {
3631
try {
37-
sortActiveSelectionInternal(JSON5, comparator);
32+
sortActiveSelectionInternal(comparator);
3833
return true;
3934
} catch (e) {
4035
console.log(e);
@@ -58,7 +53,7 @@ function setSelection(
5853
});
5954
}
6055

61-
function sortActiveSelectionInternal(jsonParser, sortOrder) {
56+
function sortActiveSelectionInternal(sortOrder) {
6257
var textEditor = vscode.window.activeTextEditor;
6358
var selection = textEditor.selection;
6459

@@ -67,8 +62,6 @@ function sortActiveSelectionInternal(jsonParser, sortOrder) {
6762
var endLine = selection.end.line;
6863
var endPos = selection.end.character;
6964

70-
var sortOptions = getConfig();
71-
7265
var selectedText = getSelection(
7366
textEditor,
7467
startLine,
@@ -78,13 +71,7 @@ function sortActiveSelectionInternal(jsonParser, sortOrder) {
7871
);
7972

8073
var indent = findIndent(textEditor);
81-
var sortedText = sorterCore.sort(
82-
selectedText,
83-
indent,
84-
jsonParser,
85-
sortOrder,
86-
sortOptions
87-
);
74+
var sortedText = sorterCore.sort(selectedText, indent, sortOrder);
8875

8976
setSelection(textEditor, startLine, startPos, endLine, endPos, sortedText);
9077
}

0 commit comments

Comments
 (0)