Files
PetCommunity/miniprogram/utils/format.ts

65 lines
2.2 KiB
TypeScript

export function formatDistance(meters: number): string {
if (meters < 1000) return `${Math.round(meters)}m`
return `${(meters / 1000).toFixed(1)}km`
}
export function formatTime(isoString: string): string {
const date = new Date(isoString)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffMin = Math.floor(diffMs / 60000)
const diffHour = Math.floor(diffMin / 60)
const diffDay = Math.floor(diffHour / 24)
if (diffMin < 1) return '刚刚'
if (diffMin < 60) return `${diffMin}分钟前`
if (diffHour < 24) return `${diffHour}小时前`
if (diffDay < 7) return `${diffDay}天前`
const month = date.getMonth() + 1
const day = date.getDate()
return `${month}${day}`
}
export function formatLastSeen(isoString: string): string {
const diffMin = Math.floor((Date.now() - new Date(isoString).getTime()) / 60000)
if (diffMin < 2) return '刚刚在线'
if (diffMin < 60) return `${diffMin}分钟前`
const diffHour = Math.floor(diffMin / 60)
if (diffHour < 24) return `${diffHour}小时前`
return '昨天在线'
}
export function formatCount(n: number): string {
if (n < 1000) return String(n)
if (n < 10000) return `${(n / 1000).toFixed(1)}k`
return `${Math.floor(n / 10000)}w`
}
export function getAvatarGradient(seed: string): string {
// 紫/冷灰单色家族,深浅交错保证相邻头像可区分
const gradients = [
'linear-gradient(135deg, #d9d2fb, #efedfd)',
'linear-gradient(135deg, #e3e5ec, #f4f5f8)',
'linear-gradient(135deg, #cfc6fa, #e9e6fc)',
'linear-gradient(135deg, #d8dbe4, #eef0f5)',
'linear-gradient(135deg, #e6e1fd, #f3f1fe)',
]
let hash = 0
for (let i = 0; i < seed.length; i++) hash = (hash * 31 + seed.charCodeAt(i)) & 0xffffffff
return gradients[Math.abs(hash) % gradients.length]
}
export function getPetEmoji(species: string, breed?: string): string {
if (species === 'cat') return '🐱'
if (species === 'other') return '🐾'
const dogBreedEmoji: Record<string, string> = {
'比熊': '🐩',
'柴犬': '🐕',
'金毛': '🦮',
'哈士奇': '🐺',
'萨摩耶': '🐕‍🦺',
}
return (breed && dogBreedEmoji[breed]) || '🐶'
}