All files / src/lib lead-city.ts

100% Statements 11/11
100% Branches 9/9
100% Functions 1/1
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36            2x                           39x 1x   38x 5x 5x 1x   4x 1x   3x   33x    
import {
	cityNameErrorMessage,
	validateCityName,
} from "@interioring/utils/validation/address";
 
/** `<select>` value that reveals the free-text city box. */
export const OTHER_CITY_VALUE = "__other__";
 
export type ResolvedLeadCity =
	| { ok: true; city: string }
	| { ok: false; message: string };
 
/**
 * The value stored on a lead: a listed city's public name, or the typed
 * "Other city" name. Empty is a validation error — callers must not submit.
 */
export function resolveSubmittedCity(
	selected: string,
	other = "",
): ResolvedLeadCity {
	if (!selected.trim()) {
		return { ok: false, message: "Please choose your city." };
	}
	if (selected === OTHER_CITY_VALUE) {
		const error = validateCityName(other);
		if (error === "required") {
			return { ok: false, message: "Please enter your city." };
		}
		if (error) {
			return { ok: false, message: cityNameErrorMessage(error) };
		}
		return { ok: true, city: other.trim().replace(/\s+/g, " ") };
	}
	return { ok: true, city: selected.trim() };
}