From 917757d14ceb0b4492e32c346c8503c375497c08 Mon Sep 17 00:00:00 2001 From: Pascal Corpet Date: Thu, 24 Jun 2021 23:11:42 +0200 Subject: [PATCH] fix: ensure complex object keys are quoted (#46) * fix: ensure complex object keys are quoted Fix #45 * style: add spacing * style: spacing Co-authored-by: Keith Cirkel --- lib/helpers.js | 14 +++++++++++++- test/objects.js | 17 +++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/lib/helpers.js b/lib/helpers.js index a3bc3a3..8a883d6 100644 --- a/lib/helpers.js +++ b/lib/helpers.js @@ -154,9 +154,21 @@ export function inspectList(list, options, inspectItem, separator = ', ') { return `${output}${truncated}` } +function quoteComplexKey(key) { + if (key.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/)) { + return key + } + return JSON.stringify(key) + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'") +} + export function inspectProperty([key, value], options) { options.truncate -= 2 - if (typeof key !== 'string' && typeof key !== 'number') { + if (typeof key === 'string') { + key = quoteComplexKey(key) + } else if (typeof key !== 'number') { key = `[${options.inspect(key, options)}]` } options.truncate -= key.length diff --git a/test/objects.js b/test/objects.js index aea8014..23beb2b 100644 --- a/test/objects.js +++ b/test/objects.js @@ -10,6 +10,23 @@ for (const [suite, inspect] of Object.entries({ expect(inspect({})).to.equal('{}') }) + it('quotes a key if it contains special chars', () => { + expect(inspect({ 'a.b': 1 })).to.equal("{ 'a.b': 1 }") + expect(inspect({ 'a b': 1 })).to.equal("{ 'a b': 1 }") + }) + + it('quotes a key if it is empty', () => { + expect(inspect({ '': 1 })).to.equal("{ '': 1 }") + }) + + it('quotes a key if it contains a single quote', () => { + expect(inspect({ "'": 1 })).to.equal("{ '\\'': 1 }") + }) + + it('quotes a key if it contains a double quote', () => { + expect(inspect({ '"': 1 })).to.equal("{ '\"': 1 }") + }) + if (suite === 'objects') { it('detects circular references', () => { const main = {}