UNPKG

sqmicro-connection

Version:

Connection abstraction for SQ Micro.

40 lines (35 loc) 1.16 kB
/** * Transform an oblect to JSON * @param {*} obj the object. * @param {number} [num=2] padding size. * @param {string|function} [circular] placeholder for circular references. A function * takes the first key under which the object was seen and returns the string, * which replaces the value. * @returns {string} json */ module.exports = function toJson(obj, num = 2, circular = defaultCircularPlaceholder) { let cache = []; if (typeof circularPlaceholder === 'string') { let placeholder = circular; circular = () => placeholder; } return JSON.stringify(obj, blockCirculars.bind(null, circular, cache, ), num); }; function blockCirculars(circular, cache, key, value) { // block internals if (key.endsWith('$')) { return `[${key}]`; } // block circulars if (typeof value === 'object' && value !== null) { let cached = cache.find(item => item.value === value); if (cached) { return circular(cached.key); } cache.push({ key, value }); } return value; } function defaultCircularPlaceholder(key) { return `[Circular ${key}]`; }