-
Notifications
You must be signed in to change notification settings - Fork 1
/
formatter.js
92 lines (72 loc) · 1.8 KB
/
formatter.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
import t from 'should-type';
function looksLikeANumber(n) {
return !!n.match(/\d+/);
}
function keyCompare(a, b) {
var aNum = looksLikeANumber(a);
var bNum = looksLikeANumber(b);
if (aNum && bNum) {
return 1*a - 1*b;
} else if (aNum && !bNum) {
return -1;
} else if (!aNum && bNum) {
return 1;
} else {
return a.localeCompare(b);
}
}
function genKeysFunc(f) {
return function(value) {
var k = f(value);
k.sort(keyCompare);
return k;
};
}
export function Formatter(opts) {
opts = opts || {};
this.seen = [];
var keysFunc;
if (typeof opts.keysFunc === 'function') {
keysFunc = opts.keysFunc;
} else if (opts.keys === false) {
keysFunc = Object.getOwnPropertyNames;
} else {
keysFunc = Object.keys;
}
this.getKeys = genKeysFunc(keysFunc);
this.maxLineLength = typeof opts.maxLineLength === 'number' ? opts.maxLineLength : 60;
this.propSep = opts.propSep || ',';
this.isUTCdate = !!opts.isUTCdate;
}
Formatter.prototype = {
constructor: Formatter,
format: function(value) {
var tp = t(value);
if (this.alreadySeen(value)) {
return '[Circular]';
}
var tries = tp.toTryTypes();
var f = this.defaultFormat;
while (tries.length) {
var toTry = tries.shift();
var name = Formatter.formatterFunctionName(toTry);
if (this[name]) {
f = this[name];
break;
}
}
return f.call(this, value).trim();
},
defaultFormat: function(obj) {
return String(obj);
},
alreadySeen: function(value) {
return this.seen.indexOf(value) >= 0;
}
};
Formatter.addType = function addType(tp, f) {
Formatter.prototype[Formatter.formatterFunctionName(tp)] = f;
};
Formatter.formatterFunctionName = function formatterFunctionName(tp) {
return '_format_' + tp.toString('_');
};