From 36be8cf909e11e51ef6b5a316c113394c27fdca0 Mon Sep 17 00:00:00 2001
From: Ruben Bridgewater <ruben@bridgewater.de>
Date: Wed, 16 Aug 2017 21:21:29 -0300
Subject: [PATCH] util: fix inspect array w. negative maxArrayLength

---
 lib/util.js                        | 7 ++++---
 test/parallel/test-util-inspect.js | 4 ++++
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/lib/util.js b/lib/util.js
index 8fe811f8121fce..f23432756568fd 100644
--- a/lib/util.js
+++ b/lib/util.js
@@ -679,11 +679,12 @@ function formatObject(ctx, value, recurseTimes, visibleKeys, keys) {
 
 
 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
+  const maxLength = Math.min(Math.max(0, ctx.maxArrayLength), value.length);
   var output = [];
   let visibleLength = 0;
   let index = 0;
   for (const elem of keys) {
-    if (visibleLength === ctx.maxArrayLength)
+    if (visibleLength === maxLength)
       break;
     // Symbols might have been added to the keys
     if (typeof elem !== 'string')
@@ -698,7 +699,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
       const message = `<${emptyItems} empty item${ending}>`;
       output.push(ctx.stylize(message, 'undefined'));
       index = i;
-      if (++visibleLength === ctx.maxArrayLength)
+      if (++visibleLength === maxLength)
         break;
     }
     output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
@@ -706,7 +707,7 @@ function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
     visibleLength++;
     index++;
   }
-  if (index < value.length && visibleLength !== ctx.maxArrayLength) {
+  if (index < value.length && visibleLength !== maxLength) {
     const len = value.length - index;
     const ending = len > 1 ? 's' : '';
     const message = `<${len} empty item${ending}>`;
diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js
index c760f2ce71738e..3252a7f0ec7d2a 100644
--- a/test/parallel/test-util-inspect.js
+++ b/test/parallel/test-util-inspect.js
@@ -960,6 +960,10 @@ if (typeof Symbol !== 'undefined') {
 {
   const x = new Array(101).fill();
   assert(!util.inspect(x, { maxArrayLength: 101 }).endsWith('1 more item ]'));
+  assert.strictEqual(
+    util.inspect(x, { maxArrayLength: -1 }),
+    '[ ... 101 more items ]'
+  );
 }
 
 {