Skip to content

Commit 8c5e9cf

Browse files
committed
feat(sort): add support for deep sorting of arrays
1 parent 4b54a22 commit 8c5e9cf

File tree

2 files changed

+34
-15
lines changed

2 files changed

+34
-15
lines changed

lib/diffURLs.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,16 @@ module.exports = async (leftURL, rightURL, opts) => {
1010
options.timeout = opts.timeout || 5000;
1111
options.headers = opts.headers || [];
1212
options.body = opts.body || [];
13-
options.sortKey = opts.sortKey || 'id';
13+
options.sortKey = opts.sortKey;
14+
options.sortKeys = opts.sortKeys || [];
1415
options.ignore = opts.ignore || [];
1516
options.skipcertificate = opts.skipcertificate || false;
1617

18+
if (options.sortKey) {
19+
options.sortKeys.unshift(options.sortKey);
20+
}
21+
options.sortKeys.push('id');
22+
1723
if (options.skipcertificate) {
1824
axios = Axios.create({
1925
httpsAgent: new https.Agent({

lib/sortArrays.js

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,29 @@
1-
module.exports = (json, options) => {
2-
let sortedJSON = {};
3-
sortedJSON = JSON.parse(JSON.stringify(json), (key, value) => {
4-
if (Array.isArray(value)) {
5-
if (typeof value[0] === 'object' && options.sortKey) {
6-
value.sort((a, b) => a[options.sortKey] - b[options.sortKey]);
7-
} else if (typeof value[0] === 'object' && value[0].id) {
8-
value.sort((a, b) => a.id - b.id);
9-
}
10-
return value.sort();
1+
function sortJSON(data, options) {
2+
const sortKeys = options.sortKeys || ['id'];
3+
4+
if (Array.isArray(data)) {
5+
if (typeof data[0] === 'object') {
6+
sortKeys.every((key) => {
7+
if (data[0][key]) {
8+
data.sort((a, b) => a[key] - b[key]);
9+
return false;
10+
}
11+
return true;
12+
});
13+
} else {
14+
data.sort();
1115
}
12-
return value;
13-
});
16+
const arr = [];
17+
data.forEach((key) => {
18+
arr.push(sortJSON(key, options));
19+
});
20+
return arr;
21+
}
22+
if (!data || typeof data !== 'object') return data;
23+
return Object.keys(data).reduce((acc, key) => {
24+
acc[key] = sortJSON(data[key], options);
25+
return acc;
26+
}, {});
27+
}
1428

15-
return sortedJSON;
16-
};
29+
module.exports = (data, options) => sortJSON(data, options);

0 commit comments

Comments
 (0)