Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 5 additions & 30 deletions lib/serializer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict'

const findEscapeSequence = /["\b\t\n\v\f\r\/]/

Check failure on line 3 in lib/serializer.js

View workflow job for this annotation

GitHub Actions / test / quality-check / Lint Code

Unnecessary escape character: \/

module.exports = class Serializer {
constructor (options) {
switch (options && options.rounding) {
Expand Down Expand Up @@ -88,37 +90,10 @@
}

asString (str) {
const len = str.length
if (len < 42) {
// magically escape strings for json
// relying on their charCodeAt
// everything below 32 needs JSON.stringify()
// every string that contain surrogate needs JSON.stringify()
// 34 and 92 happens all the time, so we
// have a fast case for them
let result = ''
let last = -1
let point = 255
for (let i = 0; i < len; i++) {
point = str.charCodeAt(i)
if (
point === 0x22 || // '"'
point === 0x5c // '\'
) {
last === -1 && (last = 0)
result += str.slice(last, i) + '\\'
last = i
} else if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) {
// The current character is non-printable characters or a surrogate.
return JSON.stringify(str)
}
}
return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
} else if (len < 5000 && str.isWellFormed()) {
// Only use the regular expression for shorter input. The overhead is otherwise too much.
return '"' + str + '"'
} else {
if (findEscapeSequence.test(str)) {
return JSON.stringify(str)
} else {
return '"' + str + '"'
}
}

Expand Down
Loading