Skip to content

Commit c688991

Browse files
committed
Add formatters + utils
1 parent 41c99e2 commit c688991

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/use/formatters.ts

+32
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,36 @@ function formatNumber(n:number, attrs?:any) {
196196
return fmtAttrs(ret, attrs)
197197
}
198198

199+
/** Format human readable ms */
200+
export function humanifyMs(ms:number): string {
201+
const seconds = Math.floor(ms / 1000)
202+
const minutes = Math.floor(seconds / 60)
203+
const hours = Math.floor(minutes / 60)
204+
const days = Math.floor(hours / 24)
205+
206+
if (days > 0) {
207+
return `${days}d ${humanifyMs(ms - days * 24 * 60 * 60_000)}`
208+
} else if (hours > 0) {
209+
return `${hours}h ${humanifyMs(ms - hours*60 * 60_000)}`
210+
} else if (minutes > 0) {
211+
return `${minutes}m ${humanifyMs(ms - minutes*60_000)}`
212+
} else if (seconds > 0) {
213+
return `${seconds}s`
214+
}
215+
return `${ms}ms`
216+
}
217+
218+
/** Format human readable number */
219+
export function humanifyNumber(n:number) {
220+
if (n >= 1_000_000_000)
221+
return (n / 1_000_000_000).toFixed(1) + "b"
222+
if (n >= 1_000_000)
223+
return (n / 1_000_000).toFixed(1) + "m"
224+
if (n >= 1_000)
225+
return (n / 1_000).toFixed(1) + "k"
226+
return n.toLocaleString()
227+
}
228+
199229
/** Format an API Response value */
200230
export function apiValueFmt(o:any, format?:FormatInfo|null, attrs?:any) {
201231
let ret = apiValue(o)
@@ -421,6 +451,8 @@ export function useFormatters() {
421451
enumFlags,
422452
formatDate,
423453
formatNumber,
454+
humanifyMs,
455+
humanifyNumber,
424456

425457
indentJson,
426458
prettyJson,

src/use/utils.ts

+5
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,10 @@ export function asOptions(all:string[],exclude?:null|string|string[]) {
244244
return all.reduce((acc:{[k:string]:boolean},x:string) => { acc[x]=!exc.includes(x); return acc }, {})
245245
}
246246

247+
export function delay(ms:number) {
248+
return new Promise(resolve => setTimeout(resolve, ms))
249+
}
250+
247251
export function useUtils() {
248252
return {
249253
LocalStore,
@@ -272,5 +276,6 @@ export function useUtils() {
272276
asStrings,
273277
asOptions,
274278
createDebounce,
279+
delay,
275280
}
276281
}

0 commit comments

Comments
 (0)