UNPKG

@stryke/json

Version:

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

42 lines (41 loc) 1.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringify = exports.invalidKeyChars = void 0; var _isNumber = require("@stryke/type-checks/is-number"); var _isUndefined = require("@stryke/type-checks/is-undefined"); const invalidKeyChars = exports.invalidKeyChars = ["@", "/", "#", "$", " ", ":", ";", ",", ".", "!", "?", "&", "=", "+", "-", "*", "%", "^", "~", "|", "\\", '"', "'", "`", "{", "}", "[", "]", "(", ")", "<", ">"], stringify = (r, e = 2) => { const n = (0, _isNumber.isNumber)(e) ? " ".repeat(e) : e; switch (r) { case null: return "null"; case void 0: return '"undefined"'; case !0: return "true"; case !1: return "false"; case Number.POSITIVE_INFINITY: return "infinity"; case Number.NEGATIVE_INFINITY: return "-infinity"; } if (Array.isArray(r)) return `[${n}${r.map(s => stringify(s, n)).join(`,${n}`)}${n}]`; if (r instanceof Uint8Array) return r.toString(); switch (typeof r) { case "number": return `${r}`; case "string": return JSON.stringify(r); case "object": { const s = Object.keys(r).filter(t => !(0, _isUndefined.isUndefined)(r[t])); return `{${n}${s.map(t => `${invalidKeyChars.some(i => t.includes(i)) ? `"${t}"` : t}: ${n}${stringify(r[t], n)}`).join(`,${n}`)}${n}}`; } default: return "null"; } }; exports.stringify = stringify;