Skip to content

Commit

Permalink
feat: add console.inspect() API for inspecting JavaScript Objects. (#691
Browse files Browse the repository at this point in the history
)

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
```
  • Loading branch information
andycall authored Nov 28, 2024
1 parent bb23eb3 commit 659e67a
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions bridge/polyfill/src/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ function formatter(obj: any, limit: number, stack: Array<any>): string {
var kind = Object.prototype.toString.call(obj).slice(8, -1);
if (kind == 'Object') {
prefix = '';
} else if (kind == 'Array') {
var itemList: any[] = obj.map((item: any) => formatter(item, limit - 1, stack));
return '[' + itemList.join(', ') + ']';
} else if (kind == 'Set') {
var itemList: any[] = [];
obj.forEach((item: any) =>itemList.push(formatter(item, limit - 1, stack)));
return 'Set {' + itemList.join(', ') + '}';
} else {
prefix = kind + ' ';
var primitive;
Expand Down Expand Up @@ -86,6 +93,10 @@ function formatter(obj: any, limit: number, stack: Array<any>): string {
var indent = INDENT.repeat(stackLength);
var keys = Object.getOwnPropertyNames(obj);

if (obj instanceof Map) {
keys = Object.keys(obj);
}

var result = prefix + '{';
if (!keys.length) {
return result + '}';
Expand Down Expand Up @@ -206,6 +217,13 @@ export const console = {
log(...args: any) {
printer(logger(arguments));
},
inspect(...args: any) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
result.push(formatter(arguments[i], Number.MAX_VALUE, []));
}
printer(result.join(SEPARATOR));
},
info(...args: any) {
printer(logger(arguments), 'info');
},
Expand Down

0 comments on commit 659e67a

Please sign in to comment.