2023-12-18 13:12:25 +08:00
|
|
|
'use strict';
|
2024-01-16 21:26:16 +08:00
|
|
|
var isPlainObj = require('is-plain-obj');
|
2023-12-18 13:12:25 +08:00
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
module.exports = function (obj, opts) {
|
2023-12-18 13:12:25 +08:00
|
|
|
if (!isPlainObj(obj)) {
|
|
|
|
throw new TypeError('Expected a plain object');
|
|
|
|
}
|
|
|
|
|
|
|
|
opts = opts || {};
|
|
|
|
|
|
|
|
// DEPRECATED
|
|
|
|
if (typeof opts === 'function') {
|
2024-01-16 21:26:16 +08:00
|
|
|
opts = {compare: opts};
|
2023-12-18 13:12:25 +08:00
|
|
|
}
|
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
var deep = opts.deep;
|
|
|
|
var seenInput = [];
|
|
|
|
var seenOutput = [];
|
2023-12-18 13:12:25 +08:00
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
var sortKeys = function (x) {
|
|
|
|
var seenIndex = seenInput.indexOf(x);
|
2023-12-18 13:12:25 +08:00
|
|
|
|
|
|
|
if (seenIndex !== -1) {
|
|
|
|
return seenOutput[seenIndex];
|
|
|
|
}
|
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
var ret = {};
|
|
|
|
var keys = Object.keys(x).sort(opts.compare);
|
2023-12-18 13:12:25 +08:00
|
|
|
|
|
|
|
seenInput.push(x);
|
|
|
|
seenOutput.push(ret);
|
|
|
|
|
2024-01-16 21:26:16 +08:00
|
|
|
for (var i = 0; i < keys.length; i++) {
|
|
|
|
var key = keys[i];
|
|
|
|
var val = x[key];
|
2023-12-18 13:12:25 +08:00
|
|
|
|
|
|
|
ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val;
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
};
|
|
|
|
|
|
|
|
return sortKeys(obj);
|
|
|
|
};
|