UNPKG

perfect-logger

Version:

A zero-dependency, isomorphic logger for Node.js and Browsers with plugin support.

27 lines (26 loc) 971 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.safeStringify = safeStringify; /** * A safe version of JSON.stringify that handles circular references. * @param obj The object to stringify. * @param replacer A function that alters the behavior of the stringification process. * @param space A String or Number object that's used to insert white space into the output JSON string for readability purposes. * @returns A JSON string. */ function safeStringify(obj, replacer, space) { const cache = new Set(); const combinedReplacer = (key, value) => { if (typeof value === 'object' && value !== null) { if (cache.has(value)) { return '[Circular]'; } cache.add(value); } if (typeof replacer === 'function') { return replacer(key, value); } return value; }; return JSON.stringify(obj, combinedReplacer, space); }