mirror of
https://github.com/CherryHQ/cherry-studio.git
synced 2026-01-06 21:35:52 +08:00
refactor(sort): replace lexicalSort with naturalSort for better string comparison
Use localeCompare with numeric sensitivity for more natural string sorting behavior
This commit is contained in:
parent
b2e2acebb1
commit
534459dd13
@ -18,17 +18,29 @@ function lexicalSort(a: string, b: string): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对对象的键按照字典序进行排序(支持嵌套对象)
|
* Natural sort function for strings, meant to be used as the sort
|
||||||
* @param obj 需要排序的对象
|
* function for `Array.prototype.sort`.
|
||||||
* @returns 返回排序后的新对象
|
*
|
||||||
|
* @param a - First element to compare.
|
||||||
|
* @param b - Second element to compare.
|
||||||
|
* @returns A number indicating which element should come first.
|
||||||
|
*/
|
||||||
|
function naturalSort(a: string, b: string): number {
|
||||||
|
return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort object keys in dictionary order (supports nested objects)
|
||||||
|
* @param obj The object to be sorted
|
||||||
|
* @returns A new object with sorted keys
|
||||||
*/
|
*/
|
||||||
export function sortedObjectByKeys(obj: object): object {
|
export function sortedObjectByKeys(obj: object): object {
|
||||||
const sortedKeys = Object.keys(obj).sort(lexicalSort)
|
const sortedKeys = Object.keys(obj).sort(naturalSort)
|
||||||
|
|
||||||
const sortedObj = {}
|
const sortedObj = {}
|
||||||
for (const key of sortedKeys) {
|
for (const key of sortedKeys) {
|
||||||
let value = obj[key]
|
let value = obj[key]
|
||||||
// 如果值是对象,递归排序
|
// If the value is an object, sort it recursively
|
||||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||||
value = sortedObjectByKeys(value)
|
value = sortedObjectByKeys(value)
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user