From 87b77656615689974607f23b136505c97d2b8275 Mon Sep 17 00:00:00 2001 From: Michael Mark Date: Sat, 25 May 2024 20:23:54 -0700 Subject: Replaced `JSON.stringify` with new `inspectString` This should be an O(n) implementation, unless string concatenation is doing something I'm not expecting. This code should be reviewed. --- src/gleam_stdlib.mjs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'src/gleam_stdlib.mjs') diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs index 256850a..2bb9386 100644 --- a/src/gleam_stdlib.mjs +++ b/src/gleam_stdlib.mjs @@ -732,7 +732,7 @@ export function inspect(v) { if (v === false) return "False"; if (v === null) return "//js(null)"; if (v === undefined) return "Nil"; - if (t === "string") return JSON.stringify(v); + if (t === "string") return inspectString(v); if (t === "bigint" || t === "number") return v.toString(); if (Array.isArray(v)) return `#(${v.map(inspect).join(", ")})`; if (v instanceof List) return inspectList(v); @@ -752,6 +752,29 @@ export function inspect(v) { return inspectObject(v); } +function inspectString(str) { + let new_str = "\""; + for (let i = 0; i < str.length; i++) { + let char = str[i]; + switch (char) { + case '\n': new_str += "\\n"; break; + case '\r': new_str += "\\r"; break; + case '\t': new_str += "\\t"; break; + case '\f': new_str += "\\f"; break; + case '\\': new_str += "\\\\"; break; + case '\"': new_str += "\\\""; break; + default: + if (char < ' ' || (char > '~' && char < '\u{00A0}')) { + new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; + } else { + new_str += char; + } + } + } + new_str += "\""; + return new_str; +} + function inspectDict(map) { let body = "dict.from_list(["; let first = true; -- cgit v1.2.3