1 var json = typeof JSON !== 'undefined' ? JSON : require('jsonify');
3 module.exports = function (obj, opts) {
5 if (typeof opts === 'function') opts = { cmp: opts };
6 var space = opts.space || '';
7 if (typeof space === 'number') space = Array(space+1).join(' ');
8 var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
9 var replacer = opts.replacer || function(key, value) { return value; };
11 var cmp = opts.cmp && (function (f) {
12 return function (node) {
13 return function (a, b) {
14 var aobj = { key: a, value: node[a] };
15 var bobj = { key: b, value: node[b] };
22 return (function stringify (parent, key, node, level) {
23 var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
24 var colonSeparator = space ? ': ' : ':';
26 if (node && node.toJSON && typeof node.toJSON === 'function') {
30 node = replacer.call(parent, key, node);
32 if (node === undefined) {
35 if (typeof node !== 'object' || node === null) {
36 return json.stringify(node);
40 for (var i = 0; i < node.length; i++) {
41 var item = stringify(node, i, node[i], level+1) || json.stringify(null);
42 out.push(indent + space + item);
44 return '[' + out.join(',') + indent + ']';
47 if (seen.indexOf(node) !== -1) {
48 if (cycles) return json.stringify('__cycle__');
49 throw new TypeError('Converting circular structure to JSON');
53 var keys = objectKeys(node).sort(cmp && cmp(node));
55 for (var i = 0; i < keys.length; i++) {
57 var value = stringify(node, key, node[key], level+1);
61 var keyValue = json.stringify(key)
65 out.push(indent + space + keyValue);
67 seen.splice(seen.indexOf(node), 1);
68 return '{' + out.join(',') + indent + '}';
70 })({ '': obj }, '', obj, 0);
73 var isArray = Array.isArray || function (x) {
74 return {}.toString.call(x) === '[object Array]';
77 var objectKeys = Object.keys || function (obj) {
78 var has = Object.prototype.hasOwnProperty || function () { return true };
80 for (var key in obj) {
81 if (has.call(obj, key)) keys.push(key);