Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -371,8 +371,14 @@ function configure (options) {
whitespace = ' '
}
const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)
if (deterministic && getTypedArrayType(value) === undefined) {
keys = sort(keys, comparator)
if (deterministic) {
if (getTypedArrayType(value) === undefined) {
keys = sort(keys, comparator)
} else if (keyLength > value.length) {
// Keep the indices in order and only sort the extra properties.
const indices = keys.slice(0, value.length)
keys = indices.concat(sort(keys.slice(value.length), comparator))
}
}
stack.push(value)
for (let i = 0; i < maximumPropertiesToStringify; i++) {
Expand Down
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,25 @@ test('omitted bigint typed array entries preserve property order and breadth',
assert.end()
})

test('replacer functions sort extra typed array properties deterministically',
/** @param {import('tap').Test} assert */
(assert) => {
const value = Object.assign(new Uint8Array([1, 2]), { z: 1, a: 2 })
const descending = /** @param {string} left @param {string} right */ (left, right) => right.localeCompare(left)
const replacer = /** @param {string} key @param {unknown} value */ (key, value) => value
for (const [deterministic, expected] of /** @type {const} */ ([
[true, { 0: 1, 1: 2, a: 2, z: 1 }],
[descending, { 0: 1, 1: 2, z: 1, a: 2 }]
])) {
const serialize = stringify.configure({ deterministic })
for (const space of [undefined, 2]) {
assert.equal(serialize(value, replacer, space), JSON.stringify(expected, null, space))
assert.equal(serialize(value, replacer, space), serialize(value, null, space))
}
}
assert.end()
})

test('bigint typed array policy uses the intrinsic type',
/** @param {import('tap').Test} assert */
(assert) => {
Expand Down