Skip to content

Commit 3ce07ce

Browse files
Align with mongo implementation per comment
1 parent babdf21 commit 3ce07ce

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

snippets/mongocompat/mongotypes.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ Array.shuffle = function(arr) {
226226
return arr;
227227
};
228228

229-
Array.tojson = function(a, indent, nolint, depth) {
229+
Array.tojson = function(a, indent, nolint, depth, sortedKeys) {
230230
if (!Array.isArray(a)) {
231231
throw new Error("The first argument to Array.tojson must be an array");
232232
}
@@ -256,7 +256,7 @@ Array.tojson = function(a, indent, nolint, depth) {
256256
indent += "\t";
257257

258258
for (var i = 0; i < a.length; i++) {
259-
s += indent + tojson(a[i], indent, nolint, depth + 1, false);
259+
s += indent + tojson(a[i], indent, nolint, depth + 1, sortedKeys);
260260
if (i < a.length - 1) {
261261
s += "," + elementSeparator;
262262
}

snippets/mongocompat/test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,11 @@ const objWithBson = {
153153
const sortedBsonJson = tojson(objWithBson, "", true, 0, true);
154154
assert(sortedBsonJson.indexOf('"a"') < sortedBsonJson.indexOf('"b"'), 'sortedkey=true should sort keys with BSON types');
155155
assert(sortedBsonJson.indexOf('"b"') < sortedBsonJson.indexOf('"c"'), 'sortedkey=true should sort keys with BSON types');
156+
const arrayWithObjects = [{ z: 1, a: 2 }, { y: 3, b: 4 }];
157+
const sortedArrayJson = Array.tojson(arrayWithObjects, "", true, 0, true);
158+
const unsortedArrayJson = Array.tojson(arrayWithObjects, "", true, 0, false);
159+
const defaultArrayJson = Array.tojson(arrayWithObjects, "", true, 0);
160+
assert(sortedArrayJson.indexOf('"a"') < sortedArrayJson.indexOf('"z"'), 'Array.tojson with sortedKeys=true should sort object keys in array elements');
161+
assert(sortedArrayJson.indexOf('"b"') < sortedArrayJson.indexOf('"y"'), 'Array.tojson with sortedKeys=true should sort object keys in array elements');
162+
assert(unsortedArrayJson.indexOf('"z"') < unsortedArrayJson.indexOf('"a"'), 'Array.tojson with sortedKeys=false should not sort keys');
163+
assert(defaultArrayJson.indexOf('"z"') < defaultArrayJson.indexOf('"a"'), 'Array.tojson without sortedKeys should not sort keys');

0 commit comments

Comments
 (0)