-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstring.ify.js
250 lines (174 loc) · 10.9 KB
/
string.ify.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"use strict";
const bullet = require ('string.bullet'),
isBrowser = (typeof window !== 'undefined') && (window.window === window) && window.navigator,
isURL = x => (typeof URL !== 'undefined') && (x instanceof URL),
maxOf = (arr, pick) => arr.reduce ((max, s) => Math.max (max, pick ? pick (s) : s), 0),
isInteger = Number.isInteger || (value => (typeof value === 'number') && isFinite (value) && (Math.floor (value) === value)),
isTypedArray = x => (x instanceof Float32Array) ||
(x instanceof Float64Array) ||
(x instanceof Int8Array) ||
(x instanceof Uint8Array) ||
(x instanceof Uint8ClampedArray) ||
(x instanceof Int16Array) ||
(x instanceof Int32Array) ||
(x instanceof Uint32Array)
const assignProps = (to, from) => { for (const prop in from) { Object.defineProperty (to, prop, Object.getOwnPropertyDescriptor (from, prop)) }; return to }
const escapeStr = x => x.replace (/\n/g, '\\n')
.replace (/\'/g, "\\'")
.replace (/\"/g, '\\"')
const { first, strlen } = require ('printable-characters') // handles ANSI codes and invisible characters
const limit = (s, n) => s && ((strlen (s) <= n) ? s : (first (s, n - 1) + '…'))
const configure = cfg => {
const stringify = x => {
const state = Object.assign ({ parents: new Set (), siblings: new Map () }, cfg)
if (cfg.pretty === 'auto') {
const oneLine = stringify.configure ({ pretty: false, siblings: new Map () }) (x)
return (oneLine.length <= cfg.maxLength) ? oneLine : stringify.configure ({ pretty: true, siblings: new Map () }) (x)
}
var customFormat = cfg.formatter && cfg.formatter (x, stringify)
if (typeof customFormat === 'string') {
return customFormat }
if ((typeof jQuery !== 'undefined') && (x instanceof jQuery)) {
x = x.toArray () }
else if (isTypedArray (x)) {
x = Array.from (x) }
else if (isURL (x)) {
x = x.toString () }
if (isBrowser && (x === window)) {
return 'window' }
else if (!isBrowser && (typeof global !== 'undefined') && (x === global)) {
return 'global' }
else if (x === null) {
return 'null' }
else if (x instanceof Date) {
return state.pure ? x.getTime () : "📅 " + x.toString () }
else if (x instanceof RegExp) {
return state.json ? '"' + x.toString () + '"' : x.toString () }
else if (state.parents.has (x)) {
return state.pure ? undefined : '<cyclic>' }
else if (!state.pure && state.siblings.has (x)) {
return '<ref:' + state.siblings.get (x) + '>' }
else if (x && (typeof Symbol !== 'undefined')
&& (customFormat = x[Symbol.for ('String.ify')])
&& (typeof customFormat === 'function')
&& (typeof (customFormat = customFormat.call (x, stringify.configure (state))) === 'string')) {
return customFormat }
else if (typeof x === 'function') {
return (cfg.pure ? x.toString () : (x.name ? ('<function:' + x.name + '>') : '<function>')) }
else if (typeof x === 'string') {
return '"' + escapeStr (limit (x, cfg.pure ? Number.MAX_SAFE_INTEGER : cfg.maxStringLength)) + '"' }
else if ((x instanceof Promise) && !state.pure) {
return '<Promise>' }
else if (typeof x === 'object') {
state.parents.add (x)
state.siblings.set (x, state.siblings.size)
const result = stringify.configure (Object.assign ({}, state, { pretty: state.pretty === false ? false : 'auto', depth: state.depth + 1 })).object (x)
state.parents.delete (x)
return result }
else if ((typeof x === 'number') && !isInteger (x) && (cfg.precision > 0)) {
return x.toFixed (cfg.precision) }
else {
return String (x) }
}
/* API */
assignProps (stringify, {
state: cfg,
configure: newConfig => configure (Object.assign ({}, cfg, newConfig)),
/* TODO: generalize generation of these chain-style .configure helpers (maybe in a separate library, as it looks like a common pattern) */
get pretty () { return stringify.configure ({ pretty: true }) },
get noPretty () { return stringify.configure ({ pretty: false }) },
get noFancy () { return stringify.configure ({ fancy: false }) },
get noRightAlignKeys () { return stringify.configure ({ rightAlignKeys: false }) },
get json () { return stringify.configure ({ json: true, pure: true }) },
get pure () { return stringify.configure ({ pure: true }) },
maxStringLength (n = Number.MAX_SAFE_INTEGER) { return stringify.configure ({ maxStringLength: n }) },
maxArrayLength (n = Number.MAX_SAFE_INTEGER) { return stringify.configure ({ maxArrayLength: n }) },
maxObjectLength (n = Number.MAX_SAFE_INTEGER) { return stringify.configure ({ maxObjectLength: n }) },
maxDepth (n = Number.MAX_SAFE_INTEGER) { return stringify.configure ({ maxDepth: n }) },
maxLength (n = Number.MAX_SAFE_INTEGER) { return stringify.configure ({ maxLength: n }) },
indentation (n) { return stringify.configure ({ indentation: n }) },
precision (p) { return stringify.configure ({ precision: p }) },
formatter (f) { return stringify.configure ({ formatter: f }) },
/* Some undocumented internals */
limit,
rightAlign: strings => {
var max = maxOf (strings, s => s.length)
return strings.map (s => ' '.repeat (max - s.length) + s) },
object: x => {
if (x instanceof Set) {
x = Array.from (x.values ()) }
else if (x instanceof Map) {
x = Array.from (x.entries ()) }
const isArray = Array.isArray (x)
if (isBrowser) {
if (x instanceof Element) {
return '<' + (x.tagName.toLowerCase () +
((x.id && ('#' + x.id)) || '') +
((x.className && ('.' + x.className)) || '')) + '>' }
else if (x instanceof Text) {
return '@' + stringify.limit (x.wholeText, 20) } }
const entries = Object.entries (x)
const tooDeep = (cfg.depth > cfg.maxDepth)
, tooBig = (isArray ? (entries.length > cfg.maxArrayLength) :
(entries.length > cfg.maxObjectLength))
if (!cfg.pure && (tooDeep || tooBig)) {
return '<' + (isArray ? 'array' : 'object') + '[' + entries.length + ']>'
}
const quoteKey = (cfg.json ? (k => '"' + escapeStr (k) + '"') :
(k => /^[A-z][A-z0-9]*$/.test (k) ? k : ("'" + escapeStr (k) + "'")))
if (cfg.pretty) {
const values = Object.values (x),
right = cfg.rightAlignKeys && cfg.fancy,
printedKeys = (right ? stringify.rightAlign : x => x) (Object.keys (x).map (k => quoteKey (k) + ': ')),
printedValues = values.map (stringify),
brace = isArray ? '[' : '{',
endBrace = isArray ? ']' : '}'
if (cfg.fancy) {
const leftPaddings = printedValues.map ((x, i) => (!right ? 0 : ((x[0] === '[') ||
(x[0] === '{'))
? 3
: ((typeof values[i] === 'string') ? 1 : 0))),
maxLeftPadding = maxOf (leftPaddings),
items = leftPaddings.map ((padding, i) => {
const value = ' '.repeat (maxLeftPadding - padding) + printedValues[i]
return isArray ? value : bullet (printedKeys[i], value)
}),
printed = bullet (brace + ' ', items.join (',\n')),
lines = printed.split ('\n'),
lastLine = lines[lines.length - 1]
return printed + (' '.repeat (maxOf (lines, l => l.length) - lastLine.length) + ' ' + endBrace)
} else {
const indent = cfg.indentation.repeat (cfg.depth)
return brace + '\n' +
printedValues.map ((x, i) => indent + (isArray ? x : (printedKeys[i] + x))).join (',\n') + '\n' +
cfg.indentation.repeat (cfg.depth - 1) +
endBrace
}
} else {
const items = entries.map (kv => (isArray ? '' : (quoteKey (kv[0]) + ': ')) + stringify (kv[1])),
content = items.join (', ')
return isArray
? ('[' + content + ']')
: ('{ ' + content + ' }')
}
}
})
return stringify
}
module.exports = configure ({
depth: 0,
pure: false,
json: false,
// color: false, // not supported yet
maxDepth: 5,
maxLength: 50,
maxArrayLength: 60,
maxObjectLength: 200,
maxStringLength: 60,
precision: undefined,
formatter: undefined,
pretty: 'auto',
rightAlignKeys: true,
fancy: true,
indentation: ' ',
})