Skip to content

Commit

Permalink
fix: properly stringify empty arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
cyyynthia committed Jan 23, 2024
1 parent 9b024b2 commit 9fb4f8b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
9 changes: 6 additions & 3 deletions src/stringify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function isArrayOfTables (obj: any[]) {
if (extendedTypeOf(obj[i]) !== 'object') return false
}

return true
return obj.length != 0
}

function formatString (s: string) {
Expand Down Expand Up @@ -84,9 +84,10 @@ function stringifyValue (val: any, type = extendedTypeOf(val)) {
}

function stringifyInlineTable (obj: any) {
let res = '{ '

let keys = Object.keys(obj)
if (keys.length === 0) return '{}'

let res = '{ '
for (let i = 0; i < keys.length; i++) {
let k = keys[i]!
if (i) res += ', '
Expand All @@ -100,6 +101,8 @@ function stringifyInlineTable (obj: any) {
}

function stringifyArray (array: any[]) {
if (array.length === 0) return '[]'

let res = '[ '
for (let i = 0; i < array.length; i++) {
if (i) res += ', '
Expand Down
15 changes: 14 additions & 1 deletion test/stringify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import { describe, it, expect } from 'vitest'
import { it, expect } from 'vitest'
import { stringify } from '../src/stringify.js'
import TomlDate from '../src/date.js'

Expand Down Expand Up @@ -93,6 +93,19 @@ a = [ 10, 20, "30", false ]
expect(stringify({ a: [ 10, 20n, '30', false ] }).trim()).toBe(expected)
})

it('stringifies empty arrays', () => {
const expected = `
a = []
[[e]]
a = []
[[e]]
`.trim()

expect(stringify({ a: [], e: [ { a: [] }, {} ] }).trim()).toBe(expected)
})

it('stringifies tables', () => {
const expected = `
[a]
Expand Down

0 comments on commit 9fb4f8b

Please sign in to comment.