Search code examples
javascriptnode.jsarraysobject

Supposed linked list example, outputs an array looking form instead of the actual object


Looking at a test code with linked lists in JavaScript below, the input parameters of the addTwoNumbers() function are objects. The actual object is shown when I stringified the parameter. Instead, a simple console.log() shows something that looks like an array but is surely not. The question here is why the simple console.log() didn't output the actual object as it should, i.e. https://onecompiler.com/javascript/3z5eafms5.

Am I missing something or is it just the platform that reforms the output in some way?

enter image description here


Solution

  • ListNode objects have a Symbol(nodejs.util.inspect.custom) method that is used by NodeJS's console.log()/util.inspect() to retrieve a representational object:

    const symbol = require('util').inspect.custom;
    // or const symbol = Symbol.for('nodejs.util.inspect.custom')
    
    console.log(Object.getPrototypeOf(l1));
    // { [Symbol(nodejs.util.inspect.custom)]: [Function (anonymous)] }
    
    console.log(typeof symbol, symbol in l1);
    // 'symbol', true
    
    class Foo {
      constructor() {
        this.foo = 42;
      }
      [symbol]() {
        return [43];
      }
    }
    
    console.log(new Foo());
    // [43]