diff --git a/index.js b/index.js index c93a915..1391fad 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,8 @@ 'use strict' const { hasOwnProperty } = Object.prototype +const { valueOf: numberValueOf } = Number.prototype +const { valueOf: stringValueOf } = String.prototype /** @typedef {{toJSON: (key: string) => unknown}} ToJSON */ @@ -199,10 +201,25 @@ function getItemCount (number) { return `${number} items` } +// Detects Number and String wrapper objects, also from other realms. +function isBoxed (value, valueOf) { + try { + valueOf.call(value) + return true + } catch { + return false + } +} + function getUniqueReplacerSet (replacerArray) { const replacerSet = new Set() for (const value of replacerArray) { - if (typeof value === 'string' || typeof value === 'number') { + if ( + typeof value === 'string' || + typeof value === 'number' || + (typeof value === 'object' && value !== null && + (isBoxed(value, numberValueOf) || isBoxed(value, stringValueOf))) + ) { replacerSet.add(String(value)) } } @@ -711,6 +728,14 @@ function configure (options) { function stringify (value, replacer, space) { if (arguments.length > 1) { let spacer = '' + // Unwrap Number and String objects like JSON.stringify does. + if (typeof space === 'object' && space !== null) { + if (isBoxed(space, numberValueOf)) { + space = Number(space) + } else if (isBoxed(space, stringValueOf)) { + space = String(space) + } + } if (typeof space === 'number') { spacer = ' '.repeat(Math.max(0, Math.min(space, 10))) } else if (typeof space === 'string') { diff --git a/test.js b/test.js index e05648c..60a9555 100644 --- a/test.js +++ b/test.js @@ -1340,6 +1340,35 @@ test('negative spacer length', function (assert) { assert.end() }) +test('Number and String objects as spacer', function (assert) { + const input = { a: [0] } + const spacers = [ + Object(2), Object(11), Object(-1), Object('--'), Object(' '.repeat(11)), + runInNewContext('Object(3)'), runInNewContext('Object("\\t")'), + // Not a Number or String object: no indentation. + Object.create(Number.prototype), Object.create(String.prototype), {} + ] + for (const space of spacers) { + assert.equal(stringify(input, null, space), JSON.stringify(input, null, space)) + } + assert.end() +}) + +test('Number and String objects in the replacer array', function (assert) { + const input = { a: 1, b: 2, 1: 3, 2: 4 } + const replacers = [ + [Object('a'), Object(1)], + [runInNewContext('Object("b")'), runInNewContext('Object(2)')], + // Not a Number or String object: ignored. + [Object.create(Number.prototype), Object.create(String.prototype), {}, null, true, 'a'] + ] + for (const replacer of replacers) { + assert.equal(stringify(input, replacer), JSON.stringify(input, replacer)) + assert.equal(stringify(input, replacer, 2), JSON.stringify(input, replacer, 2)) + } + assert.end() +}) + test('indent properly; regression test for issue #16', function (assert) { const o = { collections: {},