Skip to content

Commit 5a9ffc6

Browse files
refactor(non-blocking-json): improve it
1 parent c7d9d05 commit 5a9ffc6

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

packages/node_modules/non-blocking-json/src/index.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,4 @@ test("should handle crazy scenario", async () => {
5555
const obj = JSON.parse(string)
5656
const result = await parse(string)
5757
expect(result).toEqual(obj)
58-
})
58+
})

packages/node_modules/non-blocking-json/src/index.ts

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,19 +22,16 @@ const batch = (() => {
2222
let isRunning = false
2323
function run() {
2424
let tickLength = 0
25-
tick(() => {
26-
27-
while (currentLength && tickLength < BATCH_LENGTH) {
28-
const queueItem = queue.shift()
29-
queueItem.cb()
30-
tickLength += queueItem.length
31-
currentLength -= queueItem.length
32-
}
25+
while (currentLength && tickLength < BATCH_LENGTH) {
26+
const queueItem = queue.shift()
27+
queueItem.cb()
28+
tickLength += queueItem.length
29+
currentLength -= queueItem.length
30+
}
3331

34-
if (queue.length) {
35-
run()
36-
}
37-
})
32+
if (queue.length) {
33+
tick(run)
34+
}
3835
}
3936

4037
return (length, cb) => {
@@ -210,8 +207,8 @@ export async function parse(value) {
210207
batches.forEach((length, index) => {
211208
batch(length, () => {
212209
const startIndex = index * BATCH_LENGTH
213-
214-
for (let charIndex = startIndex; charIndex < startIndex + length; charIndex++) {
210+
let endIndex = startIndex + length
211+
for (let charIndex = startIndex; charIndex < endIndex; charIndex++) {
215212
if (value[charIndex] === '"' && value[charIndex - 1] !== '\\') {
216213
isInString = !isInString;
217214
continue;
@@ -228,16 +225,19 @@ export async function parse(value) {
228225
} else if (value[charIndex] === "}") {
229226
const openingBracketIndex = openingObjectBrackets.pop();
230227
const id = `$$REF_${refId++}`;
231-
references[id] = value.substr(
228+
const ref = value.substr(
232229
openingBracketIndex,
233230
charIndex - openingBracketIndex + 1
234231
);
232+
references[id] = ref
235233
value =
236234
value.substr(0, openingBracketIndex) +
237235
`"${id}"` +
238236
value.substr(charIndex + 1);
239237

240238
charIndex = openingBracketIndex + id.length + 1;
239+
endIndex += id.length
240+
241241
} else if (value[charIndex] === "]") {
242242
const openingBracketIndex = openingArrayBrackets.pop();
243243
const id = `$$REF_${refId++}`;
@@ -250,6 +250,7 @@ export async function parse(value) {
250250
`"${id}"` +
251251
value.substr(charIndex + 1);
252252
charIndex = openingBracketIndex + id.length + 1;
253+
endIndex += id.length
253254
}
254255
}
255256

0 commit comments

Comments
 (0)