-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
99 lines (75 loc) · 2.48 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
var JsFormatter = function() {
this.spaces = " ";
this.new_line = "\n";
var _this = this;
this.format = function(data) {
var string = '';
try
{
string = iAmFormator(JSON.parse(data), 0, false);
} catch (e) {
string = 'Not a valid json';
}
return string;
};
function getSpacesByLevel(level) {
var ret = '';
for (var x = 1; x <= level; x++) {
ret += _this.spaces;
}
return ret;
}
function iAmFormator(data, level, skip_space)
{
var level_space = getSpacesByLevel(level);
var string = (skip_space ? "" : level_space) + "{" + _this.new_line;
var iterator = 0;
for (var index in data) {
var type = typeof data[index];
iterator++;
switch (type) {
case 'object':
if (Array.isArray(data[index])) {
string += getSpacesByLevel(level + 1) + '"array": [' + data[index].join(',') + ']' + (isLast(iterator, objectLength(data)) ? '' : ',') + _this.new_line;
} else {
string += getSpacesByLevel(level + 1) + '"' + index + '": ' + iAmFormator(data[index], level + 1, true) + _this.new_line;
}
break;
case 'integer':
case 'number':
case 'string':
case 'boolean':
case 'null':
string += getSpacesByLevel(level + 1) + '"' + index + '": ' + printData(data[index], type) + (isLast(iterator, objectLength(data)) ? '' : ',') + _this.new_line;
break;
case 'function':
string += getSpacesByLevel(level + 1) + '"' + index + '": function(){}' + _this.new_line;
break;
}
}
string += level_space + "}" + _this.new_line;
return string;
}
function isLast(index, length) {
return !(index < length);
}
function objectLength(obj) {
var count = 0;
var i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
count++;
}
}
return count;
}
function printData(data, type) {
if (type == 'string') {
return '"' + data + '"';
} else {
return data;
}
}
};
var formattor = new JsFormatter();
module.exports = formattor;