55 lines
1.5 KiB
TypeScript
55 lines
1.5 KiB
TypeScript
export function cleanOptionLabel(value: string | null | undefined) {
|
|
return String(value || "")
|
|
.replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/g, "")
|
|
.replace(/\s+/g, " ")
|
|
.trim();
|
|
}
|
|
|
|
export function normalizeOptionKey(value: string | null | undefined) {
|
|
return cleanOptionLabel(value)
|
|
.normalize("NFD")
|
|
.replace(/[\u0300-\u036f]/g, "")
|
|
.toLowerCase()
|
|
.replace(/[^\p{L}\p{N}]+/gu, " ")
|
|
.trim();
|
|
}
|
|
|
|
export function canonicalOptionLabel(value: string | null | undefined) {
|
|
const cleanValue = cleanOptionLabel(value);
|
|
const key = normalizeOptionKey(cleanValue);
|
|
|
|
if (key === "republica dominicana") return "Republica Dominicana";
|
|
|
|
return cleanValue;
|
|
}
|
|
|
|
export function dedupeOptions(values: Array<string | null | undefined>) {
|
|
const unique = new Map<string, string>();
|
|
|
|
for (const value of values) {
|
|
const cleanValue = canonicalOptionLabel(value);
|
|
if (!cleanValue) continue;
|
|
|
|
const key = normalizeOptionKey(cleanValue);
|
|
if (!key) continue;
|
|
|
|
if (!unique.has(key)) {
|
|
unique.set(key, cleanValue);
|
|
}
|
|
}
|
|
|
|
return Array.from(unique.values());
|
|
}
|
|
|
|
export function ensureOption(options: string[], value: string | null | undefined) {
|
|
const uniqueOptions = dedupeOptions(options);
|
|
const current = canonicalOptionLabel(value);
|
|
|
|
if (!current) return uniqueOptions;
|
|
|
|
const currentKey = normalizeOptionKey(current);
|
|
const exists = uniqueOptions.some((option) => normalizeOptionKey(option) === currentKey);
|
|
|
|
return exists ? uniqueOptions : [current, ...uniqueOptions];
|
|
}
|