forked from derbyjs/serialize-object
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (60 loc) · 1.81 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
exports.instance = serializeInstance;
exports.args = serializeArgs;
exports.value = serializeValue;
function serializeInstance(instance) {
var args = Array.prototype.slice.call(arguments, 1);
return 'new ' + instance.module + '.' + instance.type +
'(' + serializeArgs(args) + ')';
}
function serializeArgs(args) {
// Map each argument into its string representation
var items = [];
for (var i = args.length; i--;) {
var item = serializeValue(args[i]);
items.unshift(item);
}
// Remove trailing null values, assuming they are optional
for (var i = items.length; i--;) {
var item = items[i];
if (item !== 'void 0' && item !== 'null') break;
items.pop();
}
return items.join(', ');
}
function serializeValue(input) {
if (input && input.serialize) {
return input.serialize();
} else if (typeof input === 'undefined') {
return 'void 0';
} else if (input === null) {
return 'null';
} else if (typeof input === 'string') {
return formatString(input);
} else if (typeof input === 'number' || typeof input === 'boolean') {
return input + '';
} else if (Array.isArray(input)) {
var items = [];
for (var i = 0; i < input.length; i++) {
var value = serializeValue(input[i]);
items.push(value);
}
return '[' + items.join(', ') + ']';
} else if (typeof input === 'object') {
var items = [];
for (var key in input) {
var value = serializeValue(input[key]);
items.push(formatString(key) + ': ' + value);
}
return '{' + items.join(', ') + '}';
}
}
function formatString(value) {
var escaped = value.replace(/['\r\n\\]/g, function(match) {
return (match === '\'') ? '\\\'' :
(match === '\r') ? '\\r' :
(match === '\n') ? '\\n' :
(match === '\\') ? '\\\\' :
'';
});
return '\'' + escaped + '\'';
}