Skip to content

Commit bd8029f

Browse files
committed
reimplement JSON.stringify
1 parent c1d70da commit bd8029f

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/index.ts

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ function escape(char: string) {
202202
}
203203

204204
function stringifyPrimitive(thing: any) {
205-
if (typeof thing === 'string') return JSON.stringify(thing).replace(unsafe, escape);
205+
if (typeof thing === 'string') return stringifyString(thing);
206206
if (thing === void 0) return 'void 0';
207207
if (thing === 0 && 1 / thing < 0) return '-0';
208208
const str = String(thing);
@@ -220,4 +220,27 @@ function safeKey(key: string) {
220220

221221
function safeProp(key: string) {
222222
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
223+
}
224+
225+
function stringifyString(str: string) {
226+
let result = '"';
227+
228+
for (let i = 0; i < str.length; i += 1) {
229+
const char = str[i];
230+
const code = char.charCodeAt(0);
231+
232+
if (char === '"') {
233+
result += '\\"';
234+
} else if (char in escaped) {
235+
result += escaped[char];
236+
} else if ((code >= 0xD800 && code <= 0xDBFF) && i < str.length - 1) {
237+
// escape lone surrogates
238+
result += `\\\\u${code.toString(16).toUpperCase()}`;
239+
} else {
240+
result += char;
241+
}
242+
}
243+
244+
result += '"';
245+
return result;
223246
}

0 commit comments

Comments
 (0)