@20baht/formats 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # @20baht/formats
2
2
 
3
- Named value formats. Each is three plain functions: a **check**, a **normaliser** (the one spelling to
3
+ Named value formats, and a few display formats (a relative time, a duration, money:
4
+ [below](#display-formats)). Each value format is three plain functions: a **check**, a **normaliser** (the one spelling to
4
5
  store) and a **formatter** (the spelling people read). No dependencies, no DOM; the same code runs in the
5
6
  browser and on the server.
6
7
 
@@ -71,6 +72,38 @@ form.registry = {
71
72
 
72
73
  The names are `FORMAT_NAMES`: `thaiId`, `thaiTaxId`, `thaiPhone`, `e164`, `cardNumber`, `iban`.
73
74
 
75
+ ## Display formats
76
+
77
+ Three plain functions for text people read, not values to store: no check, no normaliser. They use Intl,
78
+ so the words are CLDR's for the locale: `en` by default (as `formatRegistry`), `th`, or any BCP 47 tag.
79
+ Nothing throws: a value they cannot read, or a locale or currency Intl does not know, gives `''`.
80
+
81
+ ```ts
82
+ import { duration, money, relativeTime } from '@20baht/formats';
83
+
84
+ relativeTime(createdAt); // '5 minutes ago', against the clock
85
+ relativeTime(createdAt, { now, locale: 'th' }); // '5 นาทีที่ผ่านมา'
86
+ duration(65 * 60_000); // '1h 5m'
87
+ duration(65 * 60_000, { locale: 'th' }); // '1ชม. 5นาที'
88
+ money(1234.5, 'THB', { locale: 'th' }); // '฿1,234.50'
89
+ money('12345678901234567.89', 'USD'); // '$12,345,678,901,234,567.89'
90
+ ```
91
+
92
+ - **`relativeTime(date, { now, locale })`**: `date` is a `Date`, epoch milliseconds or a date string; `now`
93
+ defaults to `Date.now()`. The unit is the largest the gap has one whole of (second, minute, hour, day, week,
94
+ month as 30 days, year as 365), and the count is cut toward zero: 3 h 59 min is `3 hours ago`, 29 days
95
+ `4 weeks ago`. Always a number (`1 day ago`, not `yesterday`), except under a second either way: `now` /
96
+ `ขณะนี้`.
97
+ - **`duration(ms, { locale })`**: the largest unit with a whole one and the unit after it, the second left out
98
+ when it is zero, both cut, never rounded up: `1h 5m`, `1d 1h` (for 1 d 1 h 1 min 1 s), `2h` (for 2 h 30 s),
99
+ `1h 59m` (for 1 h 59 min 59 s). Units are CLDR's narrow ones, the spelling `Intl.DurationFormat`'s narrow
100
+ style gives. Days are the largest unit (`400d 3h`); under a second it shows milliseconds (`450ms`), and 0 is
101
+ `0s`. A negative duration gets a minus: `-1h 5m`.
102
+ - **`money(amount, currency, { locale })`**: `Intl.NumberFormat`'s currency style with the currency's own
103
+ decimals (`¥1,235`). `amount` is a number, a bigint or a decimal string (`-?digits(.digits)?`, as a Postgres
104
+ `numeric` arrives), and a string keeps every digit. The symbol is the locale's: `฿1,234.50` in `th`,
105
+ `THB 1,234.50` in `en` (with a no-break space).
106
+
74
107
  ## What is not here, and why
75
108
 
76
109
  - **Email.** bahtui's built-in `email` validator is loose on purpose: a strict one refuses real addresses.
@@ -0,0 +1,30 @@
1
+ export interface DisplayOptions {
2
+ /** A BCP 47 tag: `en`, `th`, `th-TH`… Default `en`, as `formatRegistry`. */
3
+ locale?: string;
4
+ }
5
+ export interface RelativeTimeOptions extends DisplayOptions {
6
+ /** The moment `date` is told against. Default the clock (`Date.now()`). */
7
+ now?: Date | number;
8
+ }
9
+ /**
10
+ * How long ago (or how far ahead) `date` is from `now`, in the largest unit it has one whole of,
11
+ * cut toward zero: `5 minutes ago`, `5 นาทีที่ผ่านมา`, `in 2 days`. Less than a second either
12
+ * way is `now` (`ขณะนี้`). Always a number (`1 day ago`, never `yesterday`: 25 hours back may be two
13
+ * calendar days back). '' when `date` or `now` cannot be read.
14
+ */
15
+ export declare function relativeTime(date: Date | number | string, options?: RelativeTimeOptions): string;
16
+ /**
17
+ * A length of time, compact: the largest unit with a whole one and the unit after it when that is
18
+ * not zero, each cut, never rounded up: `1h 5m`, `1d 1h`, `45s`; in Thai `1ชม. 5นาที`. CLDR's
19
+ * narrow units, as `Intl.DurationFormat`'s narrow style spells them. Days are the largest unit
20
+ * (`400d 3h`); under a second it is milliseconds (`450ms`), and 0 is `0s`. A negative duration
21
+ * gets a minus (`-1h 5m`). '' when `ms` is not a finite number.
22
+ */
23
+ export declare function duration(ms: number, options?: DisplayOptions): string;
24
+ /**
25
+ * An amount in a currency (ISO 4217 code), in the locale's way and the currency's own number of
26
+ * decimals: `$1,234.50`, `฿1,234.50` (`th`), `THB 1,234.50` (`en`), `¥1,235`. A decimal string
27
+ * (Postgres `numeric` as a driver hands it over) or a bigint keeps every digit. '' when the amount
28
+ * is not a finite number or a decimal, or the currency or locale is not known.
29
+ */
30
+ export declare function money(amount: number | bigint | string, currency: string, options?: DisplayOptions): string;
@@ -0,0 +1,78 @@
1
+ function attempt(fn) {
2
+ try {
3
+ return fn();
4
+ }
5
+ catch {
6
+ return '';
7
+ }
8
+ }
9
+ function timeOf(value) {
10
+ if (value instanceof Date)
11
+ return value.getTime();
12
+ if (typeof value === 'number')
13
+ return value;
14
+ return typeof value === 'string' ? Date.parse(value) : Number.NaN;
15
+ }
16
+ const SECOND = 1000;
17
+ const MINUTE = 60 * SECOND;
18
+ const HOUR = 60 * MINUTE;
19
+ const DAY = 24 * HOUR;
20
+ const RELATIVE_UNITS = [
21
+ ['year', 365 * DAY],
22
+ ['month', 30 * DAY],
23
+ ['week', 7 * DAY],
24
+ ['day', DAY],
25
+ ['hour', HOUR],
26
+ ['minute', MINUTE],
27
+ ['second', SECOND],
28
+ ];
29
+ export function relativeTime(date, options = {}) {
30
+ const diff = timeOf(date) - timeOf(options.now ?? Date.now());
31
+ if (!Number.isFinite(diff))
32
+ return '';
33
+ const locale = options.locale ?? 'en';
34
+ return attempt(() => {
35
+ for (const [unit, size] of RELATIVE_UNITS) {
36
+ if (Math.abs(diff) >= size) {
37
+ return new Intl.RelativeTimeFormat(locale, { numeric: 'always' }).format(Math.trunc(diff / size), unit);
38
+ }
39
+ }
40
+ return new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }).format(0, 'second');
41
+ });
42
+ }
43
+ const DURATION_UNITS = [
44
+ ['day', DAY],
45
+ ['hour', HOUR],
46
+ ['minute', MINUTE],
47
+ ['second', SECOND],
48
+ ];
49
+ export function duration(ms, options = {}) {
50
+ if (typeof ms !== 'number' || !Number.isFinite(ms))
51
+ return '';
52
+ const locale = options.locale ?? 'en';
53
+ const unit = (count, name) => new Intl.NumberFormat(locale, { style: 'unit', unit: name, unitDisplay: 'narrow' }).format(count);
54
+ const sign = ms < 0 ? -1 : 1;
55
+ let rest = Math.abs(ms);
56
+ return attempt(() => {
57
+ const first = DURATION_UNITS.findIndex(([, size]) => rest >= size);
58
+ if (first === -1)
59
+ return unit(sign * Math.trunc(rest), rest >= 1 ? 'millisecond' : 'second');
60
+ const parts = [];
61
+ for (const [name, size] of DURATION_UNITS.slice(first, first + 2)) {
62
+ const count = Math.trunc(rest / size);
63
+ rest -= count * size;
64
+ if (count > 0)
65
+ parts.push(unit(parts.length === 0 ? sign * count : count, name));
66
+ }
67
+ return parts.join(' ');
68
+ });
69
+ }
70
+ const DECIMAL = /^-?\d+(\.\d+)?$/;
71
+ export function money(amount, currency, options = {}) {
72
+ const readable = typeof amount === 'bigint' ||
73
+ (typeof amount === 'number' && Number.isFinite(amount)) ||
74
+ (typeof amount === 'string' && DECIMAL.test(amount));
75
+ if (!readable)
76
+ return '';
77
+ return attempt(() => new Intl.NumberFormat(options.locale ?? 'en', { style: 'currency', currency }).format(amount));
78
+ }
package/dist/index.d.ts CHANGED
@@ -2,3 +2,4 @@ export type { Format } from './format.js';
2
2
  export { thaiId, thaiPhone, thaiTaxId } from './thai.js';
3
3
  export { cardNumber, e164, iban, luhn } from './international.js';
4
4
  export { FORMAT_NAMES, formatRegistry, type FormatLocale, type FormatName, type FormatRegistry, type FormatRegistryOptions, } from './registry.js';
5
+ export { duration, money, relativeTime, type DisplayOptions, type RelativeTimeOptions, } from './display.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { thaiId, thaiPhone, thaiTaxId } from './thai.js';
2
2
  export { cardNumber, e164, iban, luhn } from './international.js';
3
3
  export { FORMAT_NAMES, formatRegistry, } from './registry.js';
4
+ export { duration, money, relativeTime, } from './display.js';
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@20baht/formats",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=20.19.0"
7
7
  },
8
- "description": "Named value formats with a check, a normaliser and a display formatter each: Thai national ID and tax ID, Thai phone numbers, E.164, card numbers (Luhn) and IBAN. No dependencies; plugs into a bahtui registry.",
8
+ "description": "Named value formats with a check, a normaliser and a display formatter each: Thai national ID and tax ID, Thai phone numbers, E.164, card numbers (Luhn) and IBAN; display formats for a relative time, a duration and money. No dependencies; plugs into a bahtui registry.",
9
9
  "license": "MIT",
10
10
  "author": "Nattapong Promthong",
11
11
  "repository": {
@@ -47,7 +47,7 @@
47
47
  "test:coverage": "vitest run --coverage"
48
48
  },
49
49
  "devDependencies": {
50
- "typescript": "^5.8.3",
50
+ "typescript": "^5.9.3",
51
51
  "vitest": "^3.2.4"
52
52
  },
53
53
  "main": "./dist/index.js",