0
# Formatting
1
2
tcompare provides powerful object formatting capabilities for converting any JavaScript value to readable string representations. The formatting system supports multiple output styles, circular reference handling, and extensive customization options.
3
4
## Capabilities
5
6
### format Function
7
8
Standalone formatting function for converting any value to a formatted string.
9
10
```typescript { .api }
11
/**
12
* Format a value and return the formatted string
13
* @param obj - The value to format
14
* @param options - Formatting options
15
* @returns Formatted string representation
16
*/
17
function format(obj: any, options?: FormatOptions): string;
18
19
/**
20
* Options to control the formatting of objects
21
*/
22
interface FormatOptions {
23
/** Sort object keys alphabetically */
24
sort?: boolean;
25
/** Formatting style - 'pretty', 'js', or 'tight' */
26
style?: StyleType;
27
/** Override buffer chunk size for Buffer display */
28
bufferChunkSize?: number;
29
/** Include enumerable properties from prototype chain */
30
includeEnumerable?: boolean;
31
/** Include getter properties */
32
includeGetters?: boolean;
33
/** Represent React elements as JSX strings (pretty style only) */
34
reactString?: boolean;
35
}
36
37
type StyleType = 'pretty' | 'js' | 'tight';
38
```
39
40
**Usage Examples:**
41
42
```typescript
43
import { format } from "tcompare";
44
45
// Basic object formatting
46
const obj = { name: "Alice", age: 25, hobbies: ["reading", "coding"] };
47
48
// Pretty style (default) - human readable
49
console.log(format(obj));
50
/*
51
Object {
52
"name": "Alice",
53
"age": 25,
54
"hobbies": Array [
55
"reading",
56
"coding",
57
],
58
}
59
*/
60
61
// JavaScript style - copy-paste friendly
62
console.log(format(obj, { style: "js" }));
63
/*
64
{
65
"name": "Alice",
66
"age": 25,
67
"hobbies": [
68
"reading",
69
"coding",
70
],
71
}
72
*/
73
74
// Tight style - minimal whitespace
75
console.log(format(obj, { style: "tight" }));
76
// {"name":"Alice","age":25,"hobbies":["reading","coding",],}
77
```
78
79
### Formatting Styles
80
81
Three distinct formatting styles for different use cases.
82
83
#### Pretty Style
84
85
Human-readable format with clear structure and type indicators.
86
87
```typescript
88
// Object notation with constructor names
89
Object {
90
"key": "value",
91
}
92
93
// Arrays with Array prefix
94
Array [
95
"item1",
96
"item2",
97
]
98
99
// Maps with entry structure
100
Map {
101
"key1" => "value1",
102
"key2" => "value2",
103
}
104
```
105
106
#### JavaScript Style
107
108
Valid JavaScript syntax suitable for copy-pasting.
109
110
```typescript
111
// Standard object literal syntax
112
{
113
"key": "value",
114
}
115
116
// Standard array syntax
117
[
118
"item1",
119
"item2",
120
]
121
122
// Map constructor syntax
123
new Map([
124
["key1", "value1"],
125
["key2", "value2"],
126
])
127
```
128
129
#### Tight Style
130
131
Minimal whitespace for compact representation.
132
133
```typescript
134
{"key":"value",}
135
["item1","item2",]
136
new Map([["key1","value1"],["key2","value2"],])
137
```
138
139
### Complex Data Types
140
141
tcompare handles all JavaScript data types with appropriate formatting.
142
143
**Arrays and Iterables:**
144
145
```typescript
146
import { format } from "tcompare";
147
148
// Regular arrays
149
console.log(format([1, 2, 3]));
150
// Array [1, 2, 3]
151
152
// Typed arrays
153
console.log(format(new Uint8Array([1, 2, 3])));
154
// Uint8Array [1, 2, 3]
155
156
// Sets
157
console.log(format(new Set(["a", "b", "c"])));
158
/*
159
Set {
160
"a",
161
"b",
162
"c",
163
}
164
*/
165
```
166
167
**Maps and Objects:**
168
169
```typescript
170
// Maps
171
const map = new Map([["key1", "value1"], ["key2", "value2"]]);
172
console.log(format(map));
173
/*
174
Map {
175
"key1" => "value1",
176
"key2" => "value2",
177
}
178
*/
179
180
// Plain objects
181
const obj = { a: 1, b: { nested: true } };
182
console.log(format(obj));
183
/*
184
Object {
185
"a": 1,
186
"b": Object {
187
"nested": true,
188
},
189
}
190
*/
191
```
192
193
**Functions and Classes:**
194
195
```typescript
196
// Functions
197
function myFunc() { return "hello"; }
198
console.log(format(myFunc));
199
// Function myFunc()
200
201
// Classes
202
class MyClass {
203
constructor(public value: number) {}
204
}
205
console.log(format(MyClass));
206
// Function MyClass(value)
207
208
// Instances
209
const instance = new MyClass(42);
210
console.log(format(instance));
211
/*
212
MyClass {
213
"value": 42,
214
}
215
*/
216
```
217
218
### Buffer Formatting
219
220
Special handling for Node.js Buffer objects with configurable chunk sizes.
221
222
```typescript { .api }
223
/**
224
* Buffer formatting options
225
*/
226
interface FormatOptions {
227
/** Number of bytes to show per line when printing long Buffers */
228
bufferChunkSize?: number; // default: 32
229
}
230
```
231
232
**Usage Examples:**
233
234
```typescript
235
import { format } from "tcompare";
236
237
const buffer = Buffer.from("Hello, World! This is a longer buffer for demo");
238
239
// Default chunk size (32 bytes)
240
console.log(format(buffer));
241
/*
242
Buffer <
243
48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21 20 54 68 |Hello, World! Th|
244
69 73 20 69 73 20 61 20 6c 6f 6e 67 65 72 20 62 |is a longer b|
245
75 66 66 65 72 20 66 6f 72 20 64 65 6d 6f |uffer for demo|
246
>
247
*/
248
249
// Custom chunk size
250
console.log(format(buffer, { bufferChunkSize: 16 }));
251
/*
252
Buffer <
253
48 65 6c 6c 6f 2c 20 57 |Hello, W|
254
6f 72 6c 64 21 20 54 68 |orld! Th|
255
69 73 20 69 73 20 61 20 |is a |
256
// ... continues
257
>
258
*/
259
```
260
261
### React Element Formatting
262
263
Special support for React JSX elements when `reactString` option is enabled.
264
265
```typescript { .api }
266
/**
267
* React element formatting options
268
*/
269
interface FormatOptions {
270
/** Represent and compare React elements as JSX strings (pretty style only) */
271
reactString?: boolean; // default: true
272
}
273
```
274
275
**Usage Examples:**
276
277
```typescript
278
import { format } from "tcompare";
279
import React from "react";
280
281
const element = React.createElement("div",
282
{ className: "container", id: "main" },
283
"Hello, World!"
284
);
285
286
// With JSX formatting (default)
287
console.log(format(element));
288
// <div className="container" id="main">Hello, World!</div>
289
290
// Without JSX formatting
291
console.log(format(element, { reactString: false }));
292
/*
293
Object {
294
"type": "div",
295
"props": Object {
296
"className": "container",
297
"id": "main",
298
"children": "Hello, World!",
299
},
300
}
301
*/
302
```
303
304
### Circular Reference Handling
305
306
Automatic detection and YAML-like reference notation for circular references.
307
308
**Usage Examples:**
309
310
```typescript
311
import { format } from "tcompare";
312
313
// Create circular reference
314
const obj: any = { name: "parent", children: [] };
315
const child = { name: "child", parent: obj };
316
obj.children.push(child);
317
318
console.log(format(obj));
319
/*
320
&ref_1 Object {
321
"name": "parent",
322
"children": Array [
323
Object {
324
"name": "child",
325
"parent": <*ref_1>,
326
},
327
],
328
}
329
*/
330
```
331
332
### Advanced Formatting Options
333
334
Additional options for specialized formatting needs.
335
336
```typescript { .api }
337
interface FormatOptions {
338
/** Sort object keys alphabetically for deterministic output */
339
sort?: boolean;
340
/** Include enumerable properties from prototype chain */
341
includeEnumerable?: boolean;
342
/** Include getter properties (may trigger side effects) */
343
includeGetters?: boolean;
344
}
345
```
346
347
**Usage Examples:**
348
349
```typescript
350
import { format } from "tcompare";
351
352
// Sorted keys for deterministic output
353
const obj = { z: 1, a: 2, m: 3 };
354
console.log(format(obj, { sort: true }));
355
/*
356
Object {
357
"a": 2,
358
"m": 3,
359
"z": 1,
360
}
361
*/
362
363
// Include prototype properties
364
class Parent {
365
parentProp = "parent";
366
}
367
class Child extends Parent {
368
childProp = "child";
369
}
370
const instance = new Child();
371
372
console.log(format(instance, { includeEnumerable: true }));
373
/*
374
Child {
375
"childProp": "child",
376
"parentProp": "parent",
377
}
378
*/
379
```
380
381
### Format Class
382
383
Direct access to the Format class for advanced usage and extending functionality.
384
385
```typescript { .api }
386
/**
387
* Base formatting class for converting values to strings
388
*/
389
class Format {
390
constructor(obj: any, options?: FormatOptions);
391
392
/** Generate formatted string representation */
393
print(): string;
394
395
/** Check if object should be treated as array */
396
isArray(): boolean;
397
398
/** Get enumerable keys from plain objects */
399
getPojoKeys(obj: any): string[];
400
401
/** Get key-value pairs from plain objects */
402
getPojoEntries(obj: any): Array<[string, any]>;
403
}
404
```
405
406
**Usage Examples:**
407
408
```typescript
409
import { Format } from "tcompare";
410
411
// Direct class usage
412
const formatter = new Format({ a: 1, b: 2 }, {
413
style: "js",
414
sort: true
415
});
416
417
const result = formatter.print();
418
console.log(result);
419
/*
420
{
421
"a": 1,
422
"b": 2,
423
}
424
*/
425
```