forked from coolaj86/json2yaml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
122 lines (102 loc) · 3.12 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
(function () {
"use strict";
var typeOf = require('remedial').typeOf,
maxText = 60,
wrap = require('wordwrap')(maxText);
function stringify(data) {
var handlers, indentLevel = '';
const depth = 0
handlers = {
"undefined": function () {
// objects will not have `undefined` converted to `null`
// as this may have unintended consequences
// For arrays, however, this behavior seems appropriate
return 'null';
},
"null": function () {
return 'null';
},
"number": function (x) {
return x;
},
"boolean": function (x) {
return x ? 'true' : 'false';
},
"string": function (x) {
var output = '|';
if (x.length <= maxText && x.indexOf('\n') === -1) {
return JSON.stringify(x);
}
var text = wrap(x).split(/\\n|\n/);
indentLevel = indentLevel.replace(/$/, ' ');
text.forEach(function (y) {
output += '\n' + indentLevel + y;
});
indentLevel = indentLevel.replace(/ /, '');
return output;
},
"date": function (x) {
return x.toJSON();
},
"array": function (x) {
var output = '';
if (0 === x.length) {
output += '[]';
return output;
}
indentLevel = indentLevel.replace(/$/, ' ');
x.forEach(function (y) {
// TODO how should `undefined` be handled?
var handler = handlers[typeOf(y)];
if (!handler) {
throw new Error('what the crap: ' + typeOf(y));
}
output += '\n' + indentLevel + '- ' + handler(y);
});
indentLevel = indentLevel.replace(/ /, '');
return output;
},
"object": function (x, depth) {
depth++
var output = '';
if (0 === Object.keys(x).length) {
output += '{}';
return output;
}
indentLevel = indentLevel.replace(/$/, depth === 1 ? '' : ' ');
Object.keys(x).forEach(function (k) {
var val = x[k],
handler = handlers[typeOf(val)];
if ('undefined' === typeof val) {
// the user should do
// delete obj.key
// and not
// obj.key = undefined
// but we'll error on the side of caution
return;
}
if (!handler) {
throw new Error('what the crap: ' + typeOf(val));
}
if (isNaN(k)) {
output += '\n' + indentLevel + k + ': ' + handler(val);
} else {
output += '\n' + indentLevel + `"${k.toString()}"` + ': ' + handler(val);
}
});
indentLevel = indentLevel.replace(/ /, '');
return output;
},
"function": function () {
// TODO this should throw or otherwise be ignored
return '[object Function]';
}
};
const output = '---' + handlers[typeOf(data)](data, depth) + '\n';
var lines = output.split('\n');
lines.splice(0,1);
var newtext = lines.join('\n');
return newtext
}
module.exports.stringify = stringify;
}());