From 6286d2ba8976aaf130088dc349e93cab2406f3af Mon Sep 17 00:00:00 2001 From: Kamil Tomsik Date: Sat, 30 Mar 2024 20:05:48 +0100 Subject: [PATCH] fmt: add humanCount() --- src/app/_util/fmt.ts | 16 +++++++++++++++- src/app/_util/index.ts | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/app/_util/fmt.ts b/src/app/_util/fmt.ts index fa17349..2507d67 100644 --- a/src/app/_util/fmt.ts +++ b/src/app/_util/fmt.ts @@ -8,7 +8,7 @@ export const dedent = (strings: TemplateStringsArray, ...values: any[]) => { } /** - * Returns a human readable string + * Returns a human readable identifier */ export const humanize = (str: string) => str @@ -16,6 +16,20 @@ export const humanize = (str: string) => .replace(/_/g, " ") .replace(/\b\w/g, l => l.toUpperCase()) +/** + * Returns a human readable count + */ +export const humanCount = (count: number) => { + switch (true) { + case count < 1_000: + return count.toString() + case count < 1_000_000: + return `${(count / 1_000).toFixed(1)}k` + default: + return `${(count / 1_000_000).toFixed(1)}m` + } +} + /** * Returns a human readable size */ diff --git a/src/app/_util/index.ts b/src/app/_util/index.ts index 9c60f2b..0be10bf 100644 --- a/src/app/_util/index.ts +++ b/src/app/_util/index.ts @@ -1,6 +1,6 @@ export { indexOf, slice } from "./array" export { err } from "./err" -export { dedent, humanSize, humanDuration, humanize } from "./fmt" +export { dedent, humanCount, humanSize, humanDuration, humanize } from "./fmt" export { jsonLines } from "./jsonLines" export { basename } from "./path" export { parseHTML } from "./parseHTML"