Munchable's paywall has to print a price on its first frame. It is the screen you land on when you run out of free scans, and a spinner where the number should be is not a thing I am willing to ship. So the currency comes off the device, synchronously, before anything has been asked of any server. I have written about what happens when that guess disagrees with what checkout charges before. This post is about the sixteen lines underneath it, which I expected to be one line.
The one line is this, and I would bet it is in production somewhere near you:
const region = locale.split('-')[1];
Here are the eight locale shapes iOS, Android and browsers actually hand you, and what that line does with them.
"en-GB" -> "GB" correct
"en_US" -> undefined
"zh-Hant-TW" -> "Hant"
"de-DE-u-ca-gregory" -> "DE" correct, by luck
"en-u-ca-gregory" -> "u"
"es-419" -> "419"
"en" -> undefined
" fr-FR " -> "FR " a trailing space
Two right, one of them only because the thing I wanted happened to be in position one, and one near miss carrying a trailing space that a currency lookup will not match. And "Hant", "u" and "419" are all answers rather than failures, which is the part that makes this worth sixteen lines.
The five ways a locale is not language-dash-country
Android uses an underscore. Locale.toString() on the JVM produces en_US, and that shape travels through various layers of React Native before anybody normalises it. Splitting on - finds nothing at all, which at least fails loudly.
A script subtag sits between the language and the region. zh-Hant-TW is Traditional Chinese as written in Taiwan. The region is the third subtag, not the second, and there is no fixed position you can index. sr-Latn-RS is the same shape for Serbian.
An extension can appear with no region in front of it. This is the one that would have cost me money. BCP 47 lets a single-character subtag open an extension, and everything after it is that extension's data:
de-DE-u-ca-gregory
^ extension starts here: "use the Gregorian calendar"
Most of the time there is a region before the extension and a naive parse survives. But en-u-ca-gregory is a perfectly legal locale with no region in it, and ca is sitting there in the string looking exactly like Canada. A parser that scans for the first two-letter subtag reads that as Canada and prints Canadian dollars to somebody in Birmingham. Nothing crashes, nothing logs, and the one person who notices is the one person who was about to pay you.
A region can be a number. es-419 is Spanish as used in Latin America, where 419 is a UN M49 code for a geographic area rather than a country. It is a legitimate region subtag, and it does not name a country, which means it does not name a currency either.
Whitespace and case. " fr-FR " and en-gb both turn up, and both have to work.
The sixteen lines
export function regionFromLocale(locale: string | null | undefined): string | null {
if (!locale) return null;
// The first subtag is the language, so the region is always one of the rest.
const [, ...subtags] = locale.trim().split(/[-_]/);
for (const subtag of subtags) {
// A single-character subtag opens an extension (`-u-ca-gregory`), and
// everything after it is extension data: `ca` there is a calendar, not
// Canada. Stop rather than read one as a country.
if (subtag.length <= 1) break;
if (/^[A-Za-z]{2}$/.test(subtag)) return subtag.toUpperCase();
}
return null;
}
Four decisions in there, each of which maps to one of the shapes above.
Splitting on [-_] takes Android's form without a separate normalisation step. Dropping the first subtag and scanning the rest means a script subtag is skipped rather than indexed around, and it generalises to shapes I have not seen. The break on a single-character subtag is the extension guard, and it is a break rather than a continue on purpose: once an extension has started, nothing after it is locale structure, so continuing to scan is exactly how you find Canada in a calendar. And ^[A-Za-z]{2}$ is what makes 419 fall through to null instead of becoming a region code the currency table would have to have an opinion about.
Why Intl.Locale is not the answer, and I checked
The obvious objection is that the platform already parses BCP 47, so why hand-roll it. Fair. I ran the same eight strings through new Intl.Locale(x).region:
"en-GB" -> "GB"
"en_US" -> RangeError: Incorrect locale information provided
"zh-Hant-TW" -> "TW"
"de-DE-u-ca-gregory" -> "DE"
"en-u-ca-gregory" -> undefined
"es-419" -> "419"
"en" -> undefined
" fr-FR " -> RangeError: Incorrect locale information provided
It is better than the one-liner and it is not sufficient. It handles the script subtag and the extension correctly, which are the two genuinely fiddly cases. But it throws on two of the eight, including the exact shape Android produces and the whitespace a trimmed string would have fixed. And it still returns "419", so you need the alpha-2 test anyway.
A throw is the problem. This function runs during the first render of a paywall. An exception there is a blank screen or a red box in front of somebody who was ready to subscribe, and the correct behaviour for an unparseable locale is not to crash, it is to shrug and print the pound price. You can wrap Intl.Locale in a try/catch and pre-trim and post-validate the region, and when you have done all three you have written sixteen lines and taken a dependency on a constructor whose availability across Hermes builds you now have to reason about. The regex version has no such question attached to it.
For what it is worth, the app does lean on Intl elsewhere, for NumberFormat, because formatting money correctly in 24 currencies is not something to hand-roll. That call site is wrapped, in exactly one place, so the assumption has one place to fail:
function money(format: () => string, pence: number): string {
try {
return format();
} catch {
return `£${(pence / 100).toFixed(2).replace(/\.00$/, '')}`;
}
}
Parse it yourself, format it with the platform. That split has held up.
Returning null is a feature, and es-419 is why
Three of the eight inputs resolve to null, and the caller treats null as "use the base currency", which is pounds, the currency the price list is actually written in.
For "en" and "" that is obviously right. For es-419 it is the interesting case, because the parse did not fail. The string genuinely contains a region. A function with one job and a loose contract would hand back 419, and then somewhere downstream a currency table either has a Latin America entry, which is a fiction, or it falls through a default and the refusal happens a long way from the information that caused it.
Latin America is not a currency area. Refusing to resolve it is the only honest answer, and the right place for that refusal is the function that can see the 419, with a test naming it:
// A UN M49 region names a continent, not a country with one currency.
assert.equal(regionFromLocale('es-419'), null);
The whole test file is the eight shapes and nothing else, with a comment on each saying which platform produces it. It is the cheapest test in this repo, it runs in plain Node with no device anywhere near it, and it is the only reason I know that en-u-ca-gregory does not resolve to Canada, because no amount of using the app would ever have shown me that.
What the sixteen lines buy
The payoff is not correctness in the abstract. It is that the paywall paints the right price on the first frame, with no request, no spinner and no number that swaps after paint, and that the one case it cannot answer gets the pound price rather than a guess.
The disagreement case still exists: the phone's region is set by its owner, the server charges in the currency of the country the request comes from, and a British phone in Spain makes those two different. That is handled a layer up, by checkout refusing to open a session for a figure the person never saw, and it is its own story.
You can see the web half of the same arrangement live: open the pricing section on munchable.app and the figure is resolved from your request rather than your device, because a page render has the request in its hands and a paywall does not. Change country with a VPN and the number changes. Change your phone's region and the app's number changes, which is the same decision made from the only signal available on the other side of the wire.
Top comments (0)