Talespin_Kit
Talespin_Kit

Reputation: 21877

Why does node.js render an array differently after I add more items to it?

Splicing the array in javascript in node console displays the outputs differently.

The sample output is shown below.

$ node
> a = [ 1, 3, 8, 5]
[ 1, 3, 8, 5 ]
> a.splice(2, 1, 4);
[ 8 ]
> a
[ 1, 3, 4, 5 ]
> a = [ 1, 3, 8, 5]
[ 1, 3, 8, 5 ]
> a.splice(2, 1, 4,6,7,8);
[ 8 ]
> a
[ 1,
  3,
  4,
  6,
  7,
  8,
  5 ]

i.e array

[1,3,4,5]

is displayed horizontally. while the array

[ 1,
  3,
  4,
  6,
  7,
  8,
  5 ]

is displayed vertically . Why is the node displaying the array vertically ?.

Upvotes: 3

Views: 213

Answers (1)

raina77ow
raina77ow

Reputation: 106375

Because it considers the output to be too long to be shown in one line - and does it a bit incorrectly.

That's how the key function looks in Node 0.10.31 (current version at the moment):

function reduceToSingleString(output, base, braces) {
  var numLinesEst = 0;
  var length = output.reduce(function(prev, cur) {
    numLinesEst++;
    if (cur.indexOf('\n') >= 0) numLinesEst++;
    return prev + cur.length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}

Source. Don't ask me what the heck numLinesEst variable is doing here. The point is, when calculating the length of each element's representation, the function doesn't take into account all the 'color' metacharacters - and there's plenty of them. That's how the length becomes much greater than '[ 1, 2, 3, 4, 5, 6 ]''s one. That's what you got now.

Now that's the same function in the most recent numbered release tag (0.11.13):

function reduceToSingleString(output, base, braces) {
  var length = output.reduce(function(prev, cur) {
    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  }, 0);

  if (length > 60) {
    return braces[0] +
           (base === '' ? '' : base + '\n ') +
           ' ' +
           output.join(',\n  ') +
           ' ' +
           braces[1];
  }

  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}

Source. The difference is obvious - all the metacharacters are excluded when the string's length is calculated.

Now guess what: that replace op was introduced into the source code by this commit from March, 2013, closing this issue.

And yes, because this issue is of very low priority, its fix is not yet in the production.

Upvotes: 4

Related Questions