Skip to content

Commit

Permalink
fix: ensure complex object keys are quoted
Browse files Browse the repository at this point in the history
  • Loading branch information
pcorpet committed Jun 10, 2021
1 parent 5db74c7 commit c9253e0
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 }")
})

describe('truncate', () => {
it('returns the full representation when truncate is over string length', () => {
expect(inspect({ a: 1, b: 2, c: 3 }, { truncate: 20 })).to.equal('{ a: 1, b: 2, c: 3 }')
Expand Down

0 comments on commit c9253e0

Please sign in to comment.