@mailbutler/i18n-utils
Version:
Manage i18n localization with static analysis
38 lines (37 loc) • 1.31 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.sortObject = sortObject;
function sortObject(object) {
const sortedObj = {}, keys = Object.keys(object);
keys.sort((key1, key2) => {
const normalizedKey1 = key1.toLowerCase();
const normalizedKey2 = key2.toLowerCase();
// Ensure prefix keys are always sorted before their longer variants (e.g. SOME before SOME_A).
if (normalizedKey1 !== normalizedKey2) {
if (normalizedKey2.startsWith(normalizedKey1))
return -1;
if (normalizedKey1.startsWith(normalizedKey2))
return 1;
}
if (normalizedKey1 < normalizedKey2)
return -1;
if (normalizedKey1 > normalizedKey2)
return 1;
// Tie-break by original key to guarantee deterministic output across platforms.
if (key1 < key2)
return -1;
if (key1 > key2)
return 1;
return 0;
});
// recursively sort object
keys.forEach((key) => {
if (typeof object[key] === 'object' && !(object[key] instanceof Array)) {
sortedObj[key] = sortObject(object[key]);
}
else {
sortedObj[key] = object[key];
}
});
return sortedObj;
}