/** * Every number an interface draws, in the language somebody chose. * * One home, because a figure is not a string until a locale has been applied to * it, and a surface that lets each screen apply its own ends up with fourteen * answers. `842` is `842` in English and `842` in French; `4,210,000` is * `4 210 000` there and `42.1 lakh` in Hindi; `$1.28M` is `1,28 M $` in * Canadian French and `128万ドル` in Japanese. Every one of those is a fact * about a reader, and `toLocaleString('en-US')` pins them all to one reader * while the language menu says otherwise. * * Nothing here rolls its own arithmetic either. A K/M/B ladder is an English * convention: CLDR gives Japanese 万 and 億 at four and eight digits rather * than three and six, and Spanish says `mil`. `Intl.NumberFormat` knows the * whole table and it is already in the browser. * * Which currency an amount can honestly be drawn in is the caller's fact and * not this module's — relabelling a dollar figure as euros is a conversion at a * rate nobody stated. So the reading arrives from outside, and everything here * is a pure function of it. */ /** Who is reading, which is the whole of what decides how a figure is written. */ export interface Reading { /** The language tag `Intl` resolves against — `en-US`, `fr-CA`, `ja`. */ locale: string /** What the amounts are stated in, as an ISO 4217 code. */ currency: string } /** * The shapes a figure is drawn in. * * Named rather than passed as options, because a shape is a decision about how * an interface reads and there are nine of them. A call site free to hand in * its own options would be a tenth place deciding how a number looks. */ type Shape = | 'count' | 'fine' | 'precise' | 'brief' | 'money' | 'offered' | 'worth' | 'percent' | 'rate' const OPTIONS: Record Intl.NumberFormatOptions> = { /** A number, grouped, to the hundredth. */ count: () => ({ maximumFractionDigits: 2 }), /** * A number under one. * * Two places after the point is right for a million and prints zero for a * thousandth, and a price printed as zero is worth less than no price at all. * Below one the digits that matter are the significant ones, so that is what * is asked for. */ fine: () => ({ maximumSignificantDigits: 4 }), /** * A quotient, at six places that mean something. * * For a figure worked out from two the chain gave — a ratio, a reserve * against a reserve. Six is enough for a price under a thousandth and short * of claiming the seventeenth digit of somebody else's arithmetic. */ precise: () => ({ maximumSignificantDigits: 6 }), /** A number short enough for a tile, in whatever short form the language has. */ brief: () => ({ notation: 'compact', maximumFractionDigits: 2 }), /** An amount, to the smallest unit the currency has. */ money: (of) => ({ style: 'currency', currency: of }), /** * A round figure a person is offered rather than one they are shown. * * No fraction, because these are whole sums somebody presses to fill a field * with, and no grouping, because they are drawn as 100, 300 and 1000. What * `Intl` is here for is the mark and where it goes: in English it leads the * digits and in Spanish it follows them, and a symbol written in front of a * number by hand is wrong in half the languages a build reads. */ offered: (of) => ({ style: 'currency', currency: of, maximumFractionDigits: 0, useGrouping: false, }), /** An amount short enough for a tile. */ worth: (of) => ({ style: 'currency', currency: of, notation: 'compact', maximumFractionDigits: 2, }), /** * A proportion, as the percentage a reader expects. * * Signed, because these sit beside a colour and the colour is not read aloud: * a screen reader that says "four point two one percent" for a fall has said * the opposite of what the row means. Zero keeps no sign, since a flat day is * neither. */ percent: () => ({ style: 'percent', signDisplay: 'exceptZero', minimumFractionDigits: 2, maximumFractionDigits: 2, }), /** * A rate, which is a percentage and not a movement. * * The same style without the sign. A charge printed as `+0.25%` reads as a * charge that went up, which is the one thing the figure does not say — and * the per-cent mark goes where the language puts it, which for Turkish is in * front of the digits. */ rate: () => ({ style: 'percent', maximumFractionDigits: 4 }), } /** * The formatters in use, kept. * * `Intl.NumberFormat` resolves a locale and loads a rule set on construction, * which is a hundred times the cost of formatting with one. A table of two * hundred rows builds two hundred of them unless somebody keeps them, and * interfaces like this draw tables of two hundred rows. * * Keyed by the three things that decide the answer. A person changing language * or currency lands on a key nothing has cached and gets a new formatter, which * is why a setting takes effect on the next paint without anything here being * told about it. */ const held = new Map() const kept = (key: string, make: () => T): T => { let it = held.get(key) if (!it) { it = make() held.set(key, it) } return it as T } /** Anything that is not a number has no rendering, and inventing one is how a * failed read reaches the screen as a figure. */ const real = (n: number): boolean => Number.isFinite(n) /** The mark a cell carries where there is nothing to draw. Not a zero: a zero * is a figure, and this is the absence of one. */ export const NONE = '—' /** Every way this reader's figures are written. */ export interface Figures { /** A number, at a resolution that suits its size. */ count(n: number | bigint): string /** A figure worked out from others, at the places the arithmetic carries. */ precise(n: number): string /** The same number, short enough to sit on one line of a tile. */ brief(n: number): string /** An amount, exact. */ money(n: number): string /** * The same amount in two pieces: what is read at full strength, and the * fraction set back behind it. * * Split by `Intl` rather than at a character, because which character * separates the two — and whether the fraction leads or trails — is a * property of the reader's language. Where there is no fraction the second * piece is empty and the caller draws one span. */ parted(n: number): readonly [string, string] /** A round sum a person is offered, in the currency the field is in. */ offered(n: number, of?: string): string /** An amount, short enough for a tile. */ worth(n: number): string /** A proportion drawn as a percentage. Takes the proportion, not the * percentage: `0.1` is ten per cent, which is what `moved` returns. */ percent(of: number): string /** A rate, as the percentage it is stated at. Takes the proportion, so a * quarter of a per cent arrives as `0.0025`. */ rate(of: number): string /** A moment, in the reader's own calendar. */ day(at: Date | number): string /** The time of day alone, for a figure re-read on a timer. */ clock(at: Date | number): string /** The same moment with the time on it. */ moment(at: Date | number): string /** * How long, in the shortest form a language has for the unit. * * English writes `10s` and `1d`; French writes `10min` and `1j`; Russian * writes `10 мин` with the space it puts there. CLDR holds all of that and * `Intl` already carries CLDR, so there is no sentence for anyone to * translate and no four-way table for anyone to get wrong. */ span(n: number, of: 'second' | 'minute' | 'hour' | 'day'): string /** * The symbol a currency is written with, out of the same source as the * figures. * * Asked of `Intl` by formatting nothing and reading back the part that is not * a digit, because there is no other way to get at it: `Intl.NumberFormat` * holds the table and does not publish it. A list of currencies draws this * beside each code, so the mark and the figures it explains cannot disagree. */ sign(of?: string): string } const sets = new Map() /** How this reader's figures are written. Kept, so a table builds one set. */ export function figures(of: Reading): Figures { const at = `${of.locale} ${of.currency}` let set = sets.get(at) if (set) return set const shape = (as: Shape, money = of.currency): Intl.NumberFormat => kept(`${as} ${of.locale} ${money}`, () => new Intl.NumberFormat(of.locale, OPTIONS[as](money))) const when = (as: string, o: Intl.DateTimeFormatOptions): Intl.DateTimeFormat => kept(`${as} ${of.locale}`, () => new Intl.DateTimeFormat(of.locale, o)) const count = (n: number | bigint): string => typeof n === 'bigint' ? shape('count').format(n) : !real(n) ? NONE : shape(Math.abs(n) < 1 && n !== 0 ? 'fine' : 'count').format(n) set = { count, precise: (n) => (!real(n) ? NONE : shape('precise').format(n)), brief: (n) => !real(n) ? NONE : Math.abs(n) < 1 && n !== 0 ? count(n) : shape('brief').format(n), money: (n) => (!real(n) ? NONE : shape('money').format(n)), parted: (n) => { if (!real(n)) return [NONE, ''] const parts = shape('money').formatToParts(n) const from = parts.findIndex((p) => p.type === 'decimal') const say = (some: Intl.NumberFormatPart[]) => some.map((p) => p.value).join('') return from < 0 ? [say(parts), ''] : [say(parts.slice(0, from)), say(parts.slice(from))] }, offered: (n, money) => shape('offered', money ?? of.currency).format(n), worth: (n) => (!real(n) ? NONE : shape('worth').format(n)), percent: (p) => (!real(p) ? NONE : shape('percent').format(p)), rate: (p) => (!real(p) ? NONE : shape('rate').format(p)), day: (at) => when('day', { dateStyle: 'medium' }).format(at), clock: (at) => when('clock', { timeStyle: 'medium' }).format(at), moment: (at) => when('moment', { dateStyle: 'medium', timeStyle: 'short' }).format(at), span: (n, unit) => kept( `span ${of.locale} ${unit}`, () => new Intl.NumberFormat(of.locale, { style: 'unit', unit, unitDisplay: 'narrow' }), ).format(n), sign: (money) => { const code = money ?? of.currency const parts = shape('money', code).formatToParts(0) return parts.find((p) => p.type === 'currency')?.value ?? code }, } sets.set(at, set) return set } /** * What a field holding a figure keeps of what was typed into it. * * Digits, at most one point, and no more places after it than the unit the * field is in carries. A field that takes more than its unit can hold has to * account for it afterwards, and an account of a keystroke is a sentence on a * screen where the honest answer is simply not to take the character. * * @param typed what arrived from the control * @param places how many decimal places the unit carries, where the field is * in a unit that says — a figure in no stated unit keeps them all */ export function digits(typed: string, places?: number): string { const parts = typed.replace(/[^0-9.]/g, '').split('.') const whole = parts[0] ?? '' if (parts.length === 1 || places === 0) return whole const after = parts.slice(1).join('') return `${whole}.${places === undefined ? after : after.slice(0, places)}` } /** * What one figure did against the one before it, as a proportion. * * A proportion rather than a percentage, because multiplying by a hundred is a * thing a reader's language does and `Intl` does it as part of drawing the * number. Arithmetic here, presentation there. * * Null rather than zero where there is nothing to compare against, and null * where the earlier figure is zero: a rise from nothing is not a proportion, * and rendering it as one puts Infinity on the screen. */ export function moved(now: number | null, before: number | null): number | null { if (now === null || before === null) return null if (!real(now) || !real(before)) return null if (before === 0) return null return (now - before) / before }