Skip to content

Commit

Permalink
fix: ensure complex object keys are quoted (#46)
Browse files Browse the repository at this point in the history
* fix: ensure complex object keys are quoted

Fix #45

* style: add spacing

* style: spacing

Co-authored-by: Keith Cirkel <keithamus@users.noreply.github.com>
  • Loading branch information
pcorpet and keithamus committed Jun 24, 2021
1 parent 1664d70 commit 917757d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions test/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}
Expand Down

0 comments on commit 917757d

Please sign in to comment.