From ee0a7c4b28d771eabd6517b134fe600894e08b51 Mon Sep 17 00:00:00 2001 From: Yarchik Date: Tue, 23 Jun 2026 00:53:41 +0100 Subject: [PATCH] fix: do not throw on a negative number `space` `JSON.stringify` treats any numeric `space` below 1 as no indentation, but `stringify` threw on it: JSON.stringify({ a: 1 }, null, -1) // '{"a":1}' stringify({ a: 1 }, null, -1) // RangeError: Invalid count value: -1 The README documents the spacer as behaving "the same as with JSON.stringify()". `space` was clamped to a maximum of 10 but not a minimum of 0, so a negative count reached `String.prototype.repeat`, which throws for counts <= -1. Clamp the lower bound to 0. --- index.js | 2 +- test.js | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 5172a71..1fcee2c 100644 --- a/index.js +++ b/index.js @@ -687,7 +687,7 @@ function configure (options) { if (arguments.length > 1) { let spacer = '' if (typeof space === 'number') { - spacer = ' '.repeat(Math.min(space, 10)) + spacer = ' '.repeat(Math.max(0, Math.min(space, 10))) } else if (typeof space === 'string') { spacer = space.slice(0, 10) } diff --git a/test.js b/test.js index 322b832..6a63d0b 100644 --- a/test.js +++ b/test.js @@ -773,6 +773,15 @@ test('maximum spacer length', function (assert) { assert.end() }) +test('negative spacer length', function (assert) { + const input = { a: 0 } + // A negative number means no indentation, same as JSON.stringify (not a throw). + assert.equal(stringify(input, null, -1), JSON.stringify(input, null, -1)) + assert.equal(stringify(input, null, -1e5), JSON.stringify(input, null, -1e5)) + assert.equal(stringify(input, null, -Infinity), JSON.stringify(input, null, -Infinity)) + assert.end() +}) + test('indent properly; regression test for issue #16', function (assert) { const o = { collections: {},