UNPKG

@stryke/json

Version:

A package containing JSON parsing/stringify utilities used by Storm Software.

43 lines (42 loc) 1.64 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stripComments = stripComments; var _base = require("@stryke/types/base"); const h = Symbol("singleComment"), a = Symbol("multiComment"); function d() { return ""; } function C(t, f, c) { return t.slice(f, c).replace(/\S/g, " "); } function y(t, f) { let c = f - 1, o = 0; for (; t[c] === "\\";) c -= 1, o += 1; return !!(o % 2); } function stripComments(t, { whitespace: f = !0, trailingCommas: c = !1 } = {}) { if (typeof t != "string") throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof t}\``); const o = f ? C : d; let g = !1, i = !1, s = 0, n = "", b = "", l = -1; for (let e = 0; e < t.length; e++) { const r = t[e], m = t[e + 1]; !i && r === '"' && (y(t, e) || (g = !g)), !g && (!i && r + (m ?? _base.EMPTY_STRING) === "//" ? (n += t.slice(s, e), s = e, i = h, e++) : i === h && r + (m ?? _base.EMPTY_STRING) === `\r ` ? (e++, i = !1, n += o(t, s, e), s = e) : i === h && r === ` ` ? (i = !1, n += o(t, s, e), s = e) : !i && r + (m ?? _base.EMPTY_STRING) === "/*" ? (n += t.slice(s, e), s = e, i = a, e++) : i === a && r + (m ?? _base.EMPTY_STRING) === "*/" ? (e++, i = !1, n += o(t, s, e + 1), s = e + 1) : c && !i && (l !== -1 ? r === "}" || r === "]" ? (n += t.slice(s, e), b += o(n, 0, 1) + n.slice(1), n = "", s = e, l = -1) : r !== " " && r !== " " && r !== "\r" && r !== ` ` && (n += t.slice(s, e), s = e, l = -1) : r === "," && (b += n + t.slice(s, e), n = "", s = e, l = e))); } return b + n + (i ? o(t.slice(s)) : t.slice(s)); }