format.ts
3.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/** 展示层格式化。统一出口,避免各面板自己写一套导致同一数值在页面上出现两种写法 */
import { UNRESOLVED_LABEL } from '@/features/heatmap/aggregate/types';
const DAY = 86400;
function pad(v: number): string {
return String(v).padStart(2, '0');
}
/** epoch 秒 → 北京时间 YYYY-MM-DD */
export function fmtDate(sec: number | null | undefined): string {
if (!sec) return '—';
const d = new Date(sec * 1000 + 8 * 3600 * 1000);
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
}
/** epoch 秒 → 北京时间 YYYY-MM-DD HH:mm */
export function fmtDateTime(sec: number | null | undefined): string {
if (!sec) return '—';
const d = new Date(sec * 1000 + 8 * 3600 * 1000);
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
}
/** 相对天数描述,用于「数据覆盖近 N 天」这类说明 */
export function spanDays(from: number, to: number): number {
return Math.max(0, Math.round((to - from) / DAY) + 1);
}
export function fmtInt(n: number): string {
return n.toLocaleString('zh-CN');
}
/** 大数压缩:图上数字与指标块共用同一套压缩规则,避免同页出现 12,345 与 1.2万 两种写法 */
export function fmtCompact(n: number): string {
if (n >= 100000000) return `${(n / 100000000).toFixed(2)}亿`;
if (n >= 10000) return `${(n / 10000).toFixed(1)}万`;
return fmtInt(n);
}
export function fmtPercent(part: number, total: number): string {
if (!total) return '0%';
return `${((part / total) * 100).toFixed(1)}%`;
}
export function fmtMs(ms: number): string {
if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`;
return `${ms.toFixed(ms >= 10 ? 0 : 1)}ms`;
}
/** 整点标签:8 → "08:00"。面板的榜头、抽屉的表格都用它,避免出现 8:00 与 08:00 两种写法 */
export function hourLabel(h: number): string {
return `${pad(h)}:00`;
}
export function fmtBytes(bytes: number): string {
if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
if (bytes >= 1024) return `${(bytes / 1024).toFixed(0)} KB`;
return `${bytes} B`;
}
/** 街道字典项 "福田区|华强北街道" → 街道名 */
export function streetNameOf(dictItem: string | undefined): string {
if (!dictItem) return '—';
const i = dictItem.indexOf('|');
return i >= 0 ? dictItem.slice(i + 1) : dictItem;
}
export function districtNameOf(dictItem: string | undefined): string {
if (!dictItem) return '—';
const i = dictItem.indexOf('|');
return i >= 0 ? dictItem.slice(0, i) : dictItem;
}
/**
* 把字典项念成「给人看的地名」:"宝安区|华强北街道" → 华强北街道,"宝安区" → 宝安区。
*
* 关键在于读不出名字时返回空串而不是「未识别」:那是「这段地址里没写出这个名字」的记号,
* 不是地名。界面上任何位置栏直接念字典下标,都会出现「有一条叫未识别的街最危险」这种
* 读法(区榜、街道榜都撤掉了,位置串也得撤)。返回空串是把决定权交回调用方:
* 清单退回坐标、明细卡显示 '—'、统计榜并入榜末那一行了结起数。
*/
export function placeNameOf(dictItem: string | undefined): string {
if (!dictItem) return '';
const name = streetNameOf(dictItem);
return name === UNRESOLVED_LABEL ? '' : name;
}