From 7e69446ac4b5becb9da0694e7bbc14799fec9dec Mon Sep 17 00:00:00 2001 From: sapphi-red Date: Sat, 2 Sep 2023 20:58:09 +0900 Subject: [PATCH 1/2] Improve stringify_string performance --- src/utils.js | 46 ++++------------------------------------------ 1 file changed, 4 insertions(+), 42 deletions(-) diff --git a/src/utils.js b/src/utils.js index 5dea3ef..c0fc375 100644 --- a/src/utils.js +++ b/src/utils.js @@ -50,50 +50,12 @@ export function get_type(thing) { return Object.prototype.toString.call(thing).slice(8, -1); } -/** @param {string} char */ -function get_escaped_char(char) { - switch (char) { - case '"': - return '\\"'; - case '<': - return '\\u003C'; - case '\\': - return '\\\\'; - case '\n': - return '\\n'; - case '\r': - return '\\r'; - case '\t': - return '\\t'; - case '\b': - return '\\b'; - case '\f': - return '\\f'; - case '\u2028': - return '\\u2028'; - case '\u2029': - return '\\u2029'; - default: - return char < ' ' - ? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}` - : ''; - } -} - +const escape_chars = /["<\\\n\r\t\b\f\u2028\u2029\x00-\x1f]/ /** @param {string} str */ export function stringify_string(str) { - let result = ''; - let last_pos = 0; - const len = str.length; - - for (let i = 0; i < len; i += 1) { - const char = str[i]; - const replacement = get_escaped_char(char); - if (replacement) { - result += str.slice(last_pos, i) + replacement; - last_pos = i + 1; - } + if (!escape_chars.test(str)){ + return `"${str}"`; } - return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`; + return JSON.stringify(str).replace(/[<\u2028\u2029]/g, char => escaped[char]); } From ad3caf0ec49c0438a825e1c9e2526c9d23846167 Mon Sep 17 00:00:00 2001 From: sapphi-red <49056869+sapphi-red@users.noreply.github.com> Date: Tue, 2 Jul 2024 00:01:18 +0900 Subject: [PATCH 2/2] Avoid callback function in replace --- src/utils.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/utils.js b/src/utils.js index 3aa2d5c..ed2a92d 100644 --- a/src/utils.js +++ b/src/utils.js @@ -51,13 +51,19 @@ export function get_type(thing) { } const escape_chars = /["<\\\n\r\t\b\f\u2028\u2029\x00-\x1f]/ +const u2028_all = /\u2028/g; +const u2029_all = /\u2029/g; +const lt_all = / escaped[char]); + return JSON.stringify(str) + .replace(u2028_all, '\\u2028') + .replace(u2029_all, '\\u2029') + .replace(lt_all, '\\u003C'); } /** @param {Record} object */