Skip to content

Commit 659e67a

Browse files
authored
feat: add console.inspect() API for inspecting JavaScript Objects. (#691)
Add a new Console API for inspecting complex JavaScript objects. Example: ```javascript const json = { name: 1, age: '2', map: new Map(), set: new Set(), fn: function() { return 1; }, undefined: undefined, null: null, nest: { nest: {aa: { arr: [1,2,3,4,5]}}} }; json.map['name'] = new Map(); json.set.add(1); json.set.add(2); json.map['name']['age'] = [1,2,3,4,5]; console.inspect(json, 2, 3,4); ``` Result: ``` { name: 1, age: '2', map: Map { name: Map { age: [1, 2, 3, 4, 5] } }, set: Set {1, 2}, fn: Function { length: 0, name: 'fn', prototype: { constructor: # } }, undefined: undefined, null: null, nest: { nest: { aa: { arr: [1, 2, 3, 4, 5] } } } } 2 3 4 ```
1 parent bb23eb3 commit 659e67a

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

bridge/polyfill/src/console.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,13 @@ function formatter(obj: any, limit: number, stack: Array<any>): string {
5555
var kind = Object.prototype.toString.call(obj).slice(8, -1);
5656
if (kind == 'Object') {
5757
prefix = '';
58+
} else if (kind == 'Array') {
59+
var itemList: any[] = obj.map((item: any) => formatter(item, limit - 1, stack));
60+
return '[' + itemList.join(', ') + ']';
61+
} else if (kind == 'Set') {
62+
var itemList: any[] = [];
63+
obj.forEach((item: any) =>itemList.push(formatter(item, limit - 1, stack)));
64+
return 'Set {' + itemList.join(', ') + '}';
5865
} else {
5966
prefix = kind + ' ';
6067
var primitive;
@@ -86,6 +93,10 @@ function formatter(obj: any, limit: number, stack: Array<any>): string {
8693
var indent = INDENT.repeat(stackLength);
8794
var keys = Object.getOwnPropertyNames(obj);
8895

96+
if (obj instanceof Map) {
97+
keys = Object.keys(obj);
98+
}
99+
89100
var result = prefix + '{';
90101
if (!keys.length) {
91102
return result + '}';
@@ -206,6 +217,13 @@ export const console = {
206217
log(...args: any) {
207218
printer(logger(arguments));
208219
},
220+
inspect(...args: any) {
221+
var result = [];
222+
for (var i = 0; i < arguments.length; i++) {
223+
result.push(formatter(arguments[i], Number.MAX_VALUE, []));
224+
}
225+
printer(result.join(SEPARATOR));
226+
},
209227
info(...args: any) {
210228
printer(logger(arguments), 'info');
211229
},

0 commit comments

Comments
 (0)