-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
56 lines (53 loc) · 1.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'use strict';
/* eslint no-implicit-coercion: 0 */
const DEFAULTS = {
depth: 2,
pretty: false
};
function replacer(maxDepth) {
const stack = [];
return function (key, value) {
if (typeof value === 'function') {
return `__Function ${value.name}(<${value.length}>)__`;
}
if (typeof value !== 'object' || value === null) {
return value;
}
const pos = stack.indexOf(this) + 1;
stack.length = pos;
if (stack.length > maxDepth) {
return '__Object__';
}
if (~stack.indexOf(value)) {
return '__Circular__';
}
if (value instanceof RegExp) {
return `__RegExp ${value.toString()}__`;
}
if (value instanceof Error) {
return `__Error ${value.toString()}__`;
}
stack.push(value);
return value;
};
}
/**
* Stringify any JS object to valid JSON
* @param {*} obj - an object to serialize
* @param {Object} [options]
* @param {number} [options.depth=2] - serialization depth
* @param {number|string|boolean} [options.pretty] - enable pretty printing
* number sets number of spaces for indentation, string - custom indentation line,
* true - sets indentation to 4 spaces
* @returns {string}
*/
function dump(obj, options) {
options = Object.assign({}, DEFAULTS, options);
if (options.pretty === true) {
options.pretty = 4;
}
return JSON.stringify(obj, replacer(options.depth), options.pretty);
}
module.exports = {
dump
};