Files
Neo-ZQYY/apps/miniprogram - 副本/miniprogram/utils/sort.ts

53 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 排序工具函数
* 纯函数,无 wx.* 依赖,可在 Node.js 测试环境中使用
*/
/**
* 按时间戳字段降序排序(最新在前)
* @param list 带时间戳字段的对象数组
* @param field 时间戳字段名,默认 'timestamp'
* @returns 排序后的新数组(不修改原数组)
*/
export function sortByTimestamp<T extends Record<string, any>>(
list: T[],
field: string = 'timestamp'
): T[] {
return [...list].sort((a, b) => {
const ta = new Date(a[field]).getTime()
const tb = new Date(b[field]).getTime()
// NaN 排到末尾
if (isNaN(ta) && isNaN(tb)) return 0
if (isNaN(ta)) return 1
if (isNaN(tb)) return -1
return tb - ta
})
}
/**
* 按指定字段排序
* @param list 对象数组
* @param field 排序字段名
* @param order 排序方向,'asc' 升序 / 'desc' 降序(默认 'desc'
* @returns 排序后的新数组
*/
export function sortByField<T extends Record<string, any>>(
list: T[],
field: string,
order: 'asc' | 'desc' = 'desc'
): T[] {
return [...list].sort((a, b) => {
const va = a[field]
const vb = b[field]
let cmp: number
if (typeof va === 'number' && typeof vb === 'number') {
cmp = va - vb
} else {
cmp = String(va ?? '').localeCompare(String(vb ?? ''))
}
return order === 'asc' ? cmp : -cmp
})
}