Skip to content

fix: sort extra typed array keys when using a replacer function - #90

Open
bardrop wants to merge 1 commit into
BridgeAR:mainfrom
bardrop-oss:fix-typed-array-replacer-sort
Open

bardrop wants to merge 1 commit into
BridgeAR:mainfrom
bardrop-oss:fix-typed-array-replacer-sort

Conversation

@bardrop

@bardrop bardrop commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

With deterministic on (the default), extra properties on a typed array are sorted. But when a replacer function is passed, they keep their insertion order instead.

const stringify = require('safe-stable-stringify')
const value = Object.assign(new Uint8Array([1, 2]), { z: 1, a: 2 })

stringify(value)
// '{"0":1,"1":2,"a":2,"z":1}'
stringify(value, (key, value) => value)
// '{"0":1,"1":2,"z":1,"a":2}'  <- not sorted

So the output depended on the order the properties were added in, which deterministic should prevent. The same happens with a custom comparator.

The no-replacer and indentation paths already keep the indices first and then sort the rest (the "omitted bigint typed array entries preserve property order and breadth" test checks this). The replacer function path skipped sorting for typed arrays completely.

Fix

In the replacer function path, keep the indices in order and sort only the extra keys, the same as the other paths.

Test

Added a test that checks the replacer function output for deterministic: true and a descending comparator, with and without space, against the expected JSON and against the output without a replacer.

  • Before the fix: { total: 84961, pass: 84957, fail: 4 }
  • After the fix: { total: 84961, pass: 84961 }

npm test (standard + tap) and npm run tsc pass.

With deterministic enabled, extra properties on a typed array were sorted
without a replacer, but kept insertion order with a replacer function.
Sort them in the replacer function path as well.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant