aboutsummaryrefslogtreecommitdiff
path: root/src/gleam_stdlib.mjs
diff options
context:
space:
mode:
authorMichael Mark <michael.mark@oit.edu>2024-05-25 20:23:54 -0700
committerLouis Pilfold <louis@lpil.uk>2024-05-29 12:26:22 +0100
commit87b77656615689974607f23b136505c97d2b8275 (patch)
tree6f15ebeacfedd59cb057ff7f36d3f010ee64f55a /src/gleam_stdlib.mjs
parentdb67449953c847934025d7f82255bad78777d207 (diff)
downloadgleam_stdlib-87b77656615689974607f23b136505c97d2b8275.tar.gz
gleam_stdlib-87b77656615689974607f23b136505c97d2b8275.zip
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.
Diffstat (limited to 'src/gleam_stdlib.mjs')
-rw-r--r--src/gleam_stdlib.mjs25
1 files changed, 24 insertions, 1 deletions
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;